您的代碼:
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
你迭代,並在其[0,0]
找到了第一位置在justTesting
始終爲0
不會改變,但我不明白爲什麼它的問題我用什麼樣的價值觀, 爲什麼索引會關心列表中的內容?
可能什麼是混淆你的事實是,index()
不搜索「抽象」的item
的出現,但它看起來在值列表中的項目的這些值與給定比較值爲item
的。也就是說,
[ab, cd, ef].index(cd)
相當於
[[0,0],[0,0],[0,0].index([0,0])
和[0,0]
值中第一次出現(!!!)爲0的索引列表,爲您的特定值a
,b
, c
,d
,e
和f
。
它應該如何告訴另一個'[0,0]'? –
'index'是一個新手陷阱;你想'枚舉'。 – user2357112
你可以用你期望的index()會做什麼以及運行你的代碼的期望結果是什麼來更新你的問題嗎? –