与python中列表的索引方法混淆。

时间:2014-01-22 05:07:34

标签: python indexing

这怎么可能?

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

2 个答案:

答案 0 :(得分:6)

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]

答案 1 :(得分: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]