【问题标题】:Confusion with the index method of a list in python.与python中列表的索引方法混淆。
【发布时间】:2014-01-22 05:07:33
【问题描述】:

这怎么可能?

list = [0, 0, 0, 0]
for i in list:
    print list.index(i),
    list[ list.index(i) ] += 1

这打印:0 1 2 3(这是可以理解的)

list = [1, 4, 5, 2]
for i in list:
    print list.index(i),
    list[ list.index(i) ] += 1

这打印:0 1 1 0

【问题讨论】:

  • 这怎么可能呢?它按预期工作。
  • 附带说明,您不应将变量命名为 list。这是内置类型和构造函数的名称。例如,如果您想从一组列表中列出一个列表,并且您已经重复使用名称 list 来表示其他含义,那么您将无法做到。
  • 认识你的新朋友enumerate. 你可以做for i, e in enumerate([1,4,5,2]): print i, e,它会做你认为应该做的事。每当您在思考for loop; wish I had the index of the elements... 时,请考虑枚举...
  • 哦,我明白了。哈哈。我已经使用这个技巧很长时间了,我什至不记得它是如何工作的。我想我不能在循环内修改它们。

标签: python indexing


【解决方案1】:

list.index(i) 返回在列表中找到值i 的第一个索引。

> i = 1
prints: 0
list[0] = 1+1 = 2 -> list = [2,4,5,2]

> i = 4
prints: 1
list[1] = 4+1 = 5 -> list = [2,5,5,2]

> i = 5
prints: 1 #because that's where 5 is first found in the list
list[1] = 5+1 = 6 -> list = [2,6,5,2]

> i = 2
prints: 0 #because that's where 2 is first found in the list
list[0] = 2+1 = 3 -> list = [3,6,5,2]

【讨论】:

  • 你还应该解释如何解决这个问题:如果你想迭代唯一索引,使用for idx, i in enumerate(lst):,然后你可以使用lst[idx],这保证是正确的,而不是@ 987654326@,可能位置不对。
【解决方案2】:

如果您修改循环以打印出更多关于正在发生的事情,您可以自己查看:

list = [0, 0, 0, 0]
for i in list:
    print i, 'found at', list.index(i), 'in', list
    list [ list.index(i) ] += 1
    print "list'", list

0 found at 0 in [0, 0, 0, 0]
list' [1, 0, 0, 0]
0 found at 1 in [1, 0, 0, 0]
list' [1, 1, 0, 0]
0 found at 2 in [1, 1, 0, 0]
list' [1, 1, 1, 0]
0 found at 3 in [1, 1, 1, 0]
list' [1, 1, 1, 1]

还有……

list = [1, 4, 5, 2]
for i in list:
    print i, 'found at', list.index(i), 'in', list
    list [ list.index(i) ] += 1
    print "list'", list

1 found at 0 in [1, 4, 5, 2]
list' [2, 4, 5, 2]
4 found at 1 in [2, 4, 5, 2]
list' [2, 5, 5, 2]
5 found at 1 in [2, 5, 5, 2]
list' [2, 6, 5, 2]
2 found at 0 in [2, 6, 5, 2]
list' [3, 6, 5, 2]

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多