列表

时间:2015-07-31 11:20:32

标签: python list indexing repeat

我在另一篇文章Index of duplicates items in a python list中看到了这个解决方案,其中明确了使用下面的代码,您可以获得列表中重复元素的索引位置。

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

def duplicates(lst, item):
       return [j for j, x in enumerate(lst) if x == item]
print(duplicates(XORcomb, 2)))

输出

[6,29​​,30]

但是,如果我尝试迭代该过程,它就不起作用。

N = [1, 2, 3, 4, 5]    

def duplicates(lst, item):
     return [i for i, x in enumerate(lst) if x == item]

for each in N:
     print("%r occurs at: %r " %(each, duplicates(XORcomb, each)))

输出

'1'出现在:[]

'2'出现在:[]

'3'出现在:[]

'4'发生在:[]

'5'出现在:[]

如果列表N是预定义的,它可以正常工作。但如果列表N是用户定义的,那么它就不起作用。

n = int(input("Enter number of values: ")) #Get user input for no. of values
N = []
for e in range (1, n+1):
     elements = input("Enter element %r: " %e)
     N.append(elements)
XORcomb = [[], [], [], [], [], [], 2, 3, 4, 5, 3, 4, 5, 4, 5, 5, 1, 6, 7, 7, 6, 1, 7, 6, 1, 1, 5, 4, 3, 2, 2, 0]
def duplicates(lst, item):
     return [j for j, x in enumerate(lst) if x == item]
for each in N:
     print("%r occurs at: %r " %(each, duplicates(XORcomb, each)))

1 个答案:

答案 0 :(得分:1)

问题是 input()会返回字符串而不是数字。运行duplicates()函数时,比较整数和字符串并得到一个空结果,因为XORcomb列表中没有字符串。

您需要先使用int()将其转换为N,然后再按n所做的那样进行转换:

>>> XORcomb = [None, None, None, None, None, None, 2, 3, 4, 5,
                  3, 4, 5, 4, 5, 5, 1, 6, 7, 7, 6, 1, 7, 6, 1, 1,
                  5, 4, 3, 2, 2, 0]
>>> N = []
>>> n = int(input("Enter number of values: "))

>>> for e in range(0, n):
       element = input("Enter element {}: ".format(str(e + 1)))
       N.append(int(element))


>>> for each in N:
     print("%r occurs at: %r " %(each, duplicates(XORcomb, each)))


1 occurs at: [16, 21, 24, 25] 
2 occurs at: [6, 29, 30] 
3 occurs at: [7, 10, 28] 
4 occurs at: [8, 11, 13, 27] 
5 occurs at: [9, 12, 14, 15, 26]