为什么索引只在我使用不同的值时才会改变?

时间:2017-08-03 22:33:14

标签: python

我刚开始用Python编程,如果我希望列表中的值相同,我就无法弄清楚如何更改索引。我想要的是索引要改变,所以它会打印0,1,2,但我得到的只是0,0,0。我试着改变列表的值,以便它们不同,然后我得到了我想要的输出。但是我不明白为什么我使用什么样的价值观,为什么索引关心列表中的内容呢?

lst = list() 
for key, val in list(counts.items()):
    lst.append((val, key)) 
    lst.sort(reverse=True) 

for key, val in lst[:10]: 
    print(key, val)

我使用python 3.6.1,如果那个垫子

5 个答案:

答案 0 :(得分:1)

因为每个列表(在循环中指定为'item')是[0,0],这意味着该行:

something = justTesting.index(item)

将在迭代期间查找列表中每个'i​​tem'的列表[0,0]的第一个实例。由于列表中的每个项目都是[0,0],因此第一个实例位于位置0。

我准备了另一个例子来说明这一点

a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
justTesting = [[a, b], [c, d], [e, f]]
for item in justTesting:
    print(item)
    something = justTesting.index(item)
    print(something)

这导致以下结果:

[1, 2]
0
[3, 4]
1
[5, 6]
2

答案 1 :(得分:0)

这是因为您的列表只包含[0, 0]

所以基本上,如果我们用它们的值替换所有变量,我们得到:

justTesting = [[0, 0], [0, 0], [0, 0]]

使用.index(item)将返回第一次出现的item(如果有的话)。由于item 总是 [0, 0]并且它首先出现在justTesting[0],因此您将始终获得0!尝试更改每个列表中的值,然后重试。例如,这有效:

b = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for item in b:
    print(b.index(item))

返回:

0, 1, 2, 3, 4, 5, 6, 7, 8

如果结果在一行上。

Try it here!

答案 2 :(得分:0)

阅读documentationindex的默认设置是识别第一次出现。您还需要使用start参数,随时更新:在最新查找之后仅搜索列表。

something = justTesting.index(item, something+1)

答案 3 :(得分:0)

那是因为你正在迭代列表。 每个项目实际上都是一个列表,并且您正在执行list.index()方法,该方法返回列表中元素的索引。

这有点棘手。由于实际上有3个列表,[0,0],在测试相等性时它们的值是相同的:

>>> a = 0
>>> b = 0
>>> c = 0
>>> d = 0
>>> ab = [a, b]
>>> cd = [c, d]
>>> 
>>> ab is cd
False
>>> ab == cd
True
>>>

现在,当您运行list.index(obj)时,您正在寻找与该对象匹配的第一个索引。您的代码实际运行list.index([0, 0]) 3次并返回第一个匹配,即索引0。 在a,b,c列表中放入不同的值,它会按预期工作。

答案 4 :(得分:0)

您的代码:

Promise.all(promises)

相当于:

a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
justTesting = [[a, b], [c, d], [e, f]]
for item in justTesting:
    something = justTesting.index(item)
    print (something)
迭代时

a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 ab = [a, b] cd = [c, d] ef = [e, f] justTesting = [ab, cd, ef] # Note that ab == cd is True and cd == ef is True # so all elements of justTesting are identical. # # for item in justTesting: # something = justTesting.index(item) # print (something) # # is essentially equivalent to: item = justTesting[0] # = ab = [0, 0] something = justTesting.index(item) # = 0 First occurrence of [0, 0] in justTesting # is **always** at index 0 item = justTesting[1] # = cd = [0, 0] something = justTesting.index(item) # = 0 item = justTesting[2] # = ef = [0, 0] something = justTesting.index(item) # = 0 不会改变,justTesting中找到justTesting第一个位置始终为0。

  

但我不明白为什么我使用的是什么样的价值,为什么索引会关注列表中的内容?

可能让您感到困惑的是,[0,0]不会在摘要中搜索index()“的出现次数,但它会查看某个项目的列出并将这些值与{{1>}的给定值进行比较。也就是说,

item

相当于

item

并且第一次出现[ab, cd, ef].index(cd) (!!!)位于[[0,0],[0,0],[0,0].index([0,0]) [0,0]特定值列表的0索引处, abcd