我有两个列表(可能会更晚一些),我想知道,在同一位置有哪个值 。
此代码返回匹配的值,但不返回匹配的位置。
a = [5,0]
b = [5,1]
print list(set(a).intersection(set(b)))
>>5
答案 0 :(得分:4)
使用zip
和enumerate
并检查唯一值:
lists = [a, b] # add more lists here if need be...
for idx, items in enumerate(zip(*lists)):
unique = set(items)
if len(unique) == 1:
# idx = position, unique.pop() == the value
print idx, unique.pop()
答案 1 :(得分:2)
def check_equal(lst):
return lst[1:] == lst[:-1]
def get_position_and_matches(*lists):
shortest_list = min(lists, key=len)
for index,item in enumerate(shortest_list):
matching = [l[index] for l in lists]
if check_equal(matching):
print "Index: {0}, Value: {1}".format(index, shortest_list[index])
one = [1, 3, 4, 6, 2]
two = [1, 3, 4, 2, 9, 9]
three = [2, 3, 4]
get_position_and_matches(one, two, three)
答案 2 :(得分:1)
您可以编写自己的方法:
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
c = [3, 3, 3, 3, 3]
allLists = [b, c] # all lists but the first
for i in range(len(a)):
good = True
for l in allLists:
if l[i] != a[i]:
good = False
break
if good:
print(i, a[i])
编辑以便于添加更多列表
答案 3 :(得分:1)
这将显示匹配的位置(假设值None不是有效元素)
a=[1,2,3]
b=[0,2,3]
c=[3,2,1]
l = [a, b, c] # add any number of lists
z = zip(*l)
pos = 0
for i in z:
if reduce(lambda x, y: x if x == y else None, i):
print pos
pos += 1
或者,如果你想保持每个位置的匹配:
matches=[reduce(lambda x, y: x if x == y else None, i) for i in z]
会产生
[None, 2, None]
答案 4 :(得分:0)
matching_indexes = [i for i in range(len(a)) if a[i] == b[i] == c[i]]
可以使用。一个简单的列表理解,用于测试a,b和c的每个单独的值。可以为每个要比较的列表添加或多或少的==
。但是,这假定所有列表的长度相同或者a是最短的列表。
答案 5 :(得分:0)
这是您想要使用的列表的答案
a = [5,0,1,2]
b = [5,2,3,2]
lists = [a,b,b,a,a]
d = dict()
for l in lists:
for i in range(len(a)):
if i not in d.keys():
d[i] = a[i]
elif d[i] != l[i]:
d[i] = -1
for i in d.keys():
if d[i] != -1:
print d[i], i