2017-08-03 45 views
-2

我剛剛開始用Python進行編程,我不知道如何讓索引更改,如果我想要列表中的值是相同的。我想要的是索引改變,所以它會打印0,1,2,但我得到的是0,0,0。我試圖改變列表的值,使它們不同,然後我得到我想要的輸出。但我不明白爲什麼它使用什麼樣的價值觀,爲什麼索引會關心列表中的內容?爲什麼只有當我使用不同的值時,指數纔會變化?

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) 

我使用python 3.6.1如果mattters

+4

它應該如何告訴另一個'[0,0]'? –

+2

'index'是一個新手陷阱;你想'枚舉'。 – user2357112

+0

你可以用你期望的index()會做什麼以及運行你的代碼的期望結果是什麼來更新你的問題嗎? –

回答

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!

0

閱讀documentation:爲index默認是識別第一 occurence。您還需要使用start參數,並隨時更新:在之後搜索最近查找的列表

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

那是因爲你迭代列表的列表。 每個項目實際上是一個列表,並且您正在執行list.index()方法,該方法返回列表中元素的索引。

這有點棘手。當您運行list.index(obj)你正在尋找的對象相匹配的第一個指數

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

現在:既然你確實有3名名單,[0,0]它們的值將平等測試時是相同的。您的代碼實際上運行了list.index([0, 0]) 3次,並返回索引爲0的第一個匹配項。 將不同的值放入a,b,c列表中,它將按預期工作。

1

因爲每個列表(指定在循環「項目」)爲[0,0],這意味着該行:

something = justTesting.index(item) 

會尋找名單的[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 
0

您的代碼:

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的索引列表,爲您的特定值abcd,ef

相關問題