列表索引必须是整数,而不是列表

时间:2013-10-15 23:41:15

标签: python list

我有一个随机数列表。 我想知道该列表中的数字是否在另一个列表中。

出于某种原因,它告诉我“列表索引必须是整数,而不是列表”

我知道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) ]

所以a是一个随机整数列表

我有一个名为unique的函数,我调用unique(a)

这是我得到的确切错误:

导入随机

a = [random.randrange(20)for _ in range(20)]

独特的(a)

追踪(最近一次呼叫最后一次):

文件“”,第1行,

文件“a5.py”,第8行,唯一

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

TypeError:列表索引必须是整数,而不是列表

1 个答案:

答案 0 :(得分:1)

如果您想知道数字是否在数字列表中,请执行以下操作:

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

如果您想知道列表中的 where ,请使用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号,你需要减少海洛因(如果你=''William S. Burroughs')或更少的坏电影角色(如果你= ='吉姆卡里')。