2013-10-15 124 views
-1

我有一個隨機數列表。 我想知道該列表中的數字是否在另一個列表中。列表索引必須是整數,而不是列表

出於某種原因,它告訴我「列表索引必須是整數,沒有列出」

我知道,一個int是不一樣的列表中的一個int值。我只是不確定我是如何看待他們是否相同。

如何將int與列表中的數字進行比較將非常感謝。 我已經瀏覽了這裏和不同的網站,並且沒有我遇到的示例幫助我;或者我只是不明白他們的解決方案。

再次感謝。

編輯:

這裏是我的代碼以「數字列表」的一部分,但它仍然有同樣的錯誤出現。

b = [] 

for i in range(len(a)): #goes through the list of numbers 
    for j in (i, range(len(a))): #checks if the first numbers appears again 
     for q in (0, range(len(b))): #checks if that number is in the 
      if (a[i] == a[j] and a[i] in b == true): #the second list 
       b.append(a[i]) 
      else: 
       continue 
return b 

我得到我的錯誤在第一if聲明

編輯2: import random a = [ random.randrange(20) for _ in range(20) ]

所以是隨機整數

的名單我已經叫獨特的功能和我打電話unique(a)

這是我得到的確切錯誤:

進口隨機

A = [random.randrange(20)_範圍內(20)]

唯一的(一)

回溯(最近通話最後一個):

文件「」,第1行,在

文件「a5。PY」,8號線,在獨特的

if (a[i] == a[j] and temp in b == true): 

類型錯誤:列表索引必須是整數,沒有列出

+4

向我們展示您的代碼,它會幫助我們幫助您。 – squiguy

回答

1

如果你想找出一個數是否是號碼清單,只是這樣做:

>>> list_of_numbers = [10, 20, 30, 40] 
>>> number = 20 
>>> number in list_of_numbers 
True 

如果你想知道哪裏名單是,使用index

>>> list_of_numbers.index(number) 
1 
>>> list_of_numbers[1] 
20 

如果你想知道它出現在列表中的所有的地方,你將不得不寫一個明確的循環語句或理解:

>>> list_of_numbers = [10, 20, 30, 10, 20, 30] 
>>> [index for index, element in list_of_numbers if element == number] 
1, 5 

如果你想知道是否有任何數字的一個列表如果你想知道有多少在一個列表中的數字是在另一個

>>> other_list = [1, 10, 100, 1000] 
>>> set(other_list).intersection(list_of_numbers) 
{10} 

:也是另一個,這樣做

>>> other_list = [1, 10, 100, 1000] 
>>> len(set(other_list).intersection(list_of_numbers)) 
1 

如果你想知道數字23是否出現在你有的每一個列表中,你需要採取更少的海洛因(如果你=='威廉S.Burroughs')或更少的壞電影角色(如果你==金凱瑞「)。

+0

我嘗試了列表中的數字,它仍然不起作用 –

+0

@Gabriel,我們看不到您嘗試過的,您必須將它發佈到您的問題。並說什麼「沒有工作」的意思。 –

+0

噢,天啊,我很抱歉,答案在這個原始答案中是正確的。我只是讀了第一次才明白它。謝謝你。非常感謝。 –

相關問題