tgctg2020 发表于 2020-12-17 10:54:26

这是怎么回事?


>>> n=list(range(10))
>>> n

>>> i=enumerate(n)
>>> list(i)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> reversed(list(i))
<list_reverseiterator object at 0x000001ED5850E248>
>>> list(reversed(list(1)))
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
    list(reversed(list(1)))
TypeError: 'int' object is not iterable
>>> list(i)
[]
>>>


为什么list(reversed(list(1)))会报错?为什么list(i)的值会变成[]???

小伤口 发表于 2020-12-17 11:35:12

本帖最后由 小伤口 于 2020-12-17 11:36 编辑

enumerate()遍历数据,同时输出数据与索引
类似于for循环,只是遍历
遍历一次之后自然为空>>> n=list(range(10))
>>> n

>>> i=enumerate(n)
>>> list(i)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> list(i)
[]
>>> for i in range(5):
        print(i)

       
0
1
2
3
4
>>> print(i)
4
>>>
而你报错的原因是list(reversed(list(1)))
里面是i不是1list(reversed(list(i)))
[(9, 9), (8, 8), (7, 7), (6, 6), (5, 5), (4, 4), (3, 3), (2, 2), (1, 1), (0, 0)]
要想保存数据应该提前赋值>>> i=enumerate(n)
>>> a=list(i)
>>> a
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> a
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>>

jackz007 发表于 2020-12-17 11:59:40

      这一句写错了吧
ist(reversed(list(1)))
      应该是下面这样才对
list(reversed(list(i)))
页: [1]
查看完整版本: 这是怎么回事?