相关疑难解决方法(0)

在Python中,如何确定对象是否可迭代?

有方法isiterable吗?到目前为止我找到的唯一解决方案是打电话

hasattr(myObj, '__iter__')
Run Code Online (Sandbox Code Playgroud)

但我不确定这是多么万无一失.

python iterable

994
推荐指数
14
解决办法
41万
查看次数

__iter__和__getitem__之间有什么区别?

对于我来说,这在Python 2.7.6和3.3.3中会发生.当我定义这样的类时

class foo:
    def __getitem__(self, *args):
        print(*args)
Run Code Online (Sandbox Code Playgroud)

然后尝试在一个实例上迭代(以及我认为会称之为iter),

bar = foo()
for i in bar:
    print(i)
Run Code Online (Sandbox Code Playgroud)

它只是为一个args计算,并永远打印无.就语言设计而言,这是故意的吗?

样本输出

0
None
1
None
2
None
3
None
4
None
5
None
6
None
7
None
8
None
9
None
10
None
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x

14
推荐指数
2
解决办法
6888
查看次数

在python中使用__getitem__迭代字典

我已经实现了一个 python 类来生成数据,如下所示:

class Array:
    def __init__(self):
        self.arr = [1,2,3,4,5,6,7,8]

    def __getitem__(self,key):
        return self.arr[key]

a = Array()
for i in a:
    print(i, end = " ")
Run Code Online (Sandbox Code Playgroud)

它按预期运行,我得到了关注

1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)

但是,我想对字典做同样的事情。为什么我不能像这样迭代字典?

class Dictionary:
    def __init__(self):
        self.dictionary = {'a' : 1, 'b' : 2, 'c': 3}

    def __getitem__(self,key):
        return self.dictionary[key]
d = Dictionary()
for key in d:
    print(key, d[key], end=" ")
Run Code Online (Sandbox Code Playgroud)

我希望以下输出

a 1 b 2 c 3
Run Code Online (Sandbox Code Playgroud)

但是当我运行上面的代码时,出现以下错误:

Traceback (most recent call last):

  File "<ipython-input-33-4547779db7ec>", …
Run Code Online (Sandbox Code Playgroud)

python dictionary iterator python-3.x

8
推荐指数
2
解决办法
798
查看次数

__iter__中__getitem__的等效代码

我试图__iter__在Python 3中更多地了解.出于某些原因__getitem__,我更好地理解__iter__.我想我不知道怎么没有得到相应的下一个实现__iter__.

我有以下代码:

class Item:
    def __getitem__(self,pos):
        return range(0,30,10)[pos]

item1= Item()
print (f[1]) # 10
for i in item1:
   print (i) # 0 10 20
Run Code Online (Sandbox Code Playgroud)

我理解上面的代码,但是又如何使用__iter__和编写等效代码__next__()

class Item:
   def __iter__(self):
      return self
      #Lost here
   def __next__(self,pos):
      #Lost here
Run Code Online (Sandbox Code Playgroud)

我理解当python看到一个__getitem__方法时,它会尝试通过调用带有整数索引的方法来迭代该对象0.

python iterator python-3.x

0
推荐指数
1
解决办法
413
查看次数

标签 统计

python ×4

python-3.x ×3

iterator ×2

dictionary ×1

iterable ×1

python-2.7 ×1