我正在尝试写一个程序,它可以检查两个列表,如果两个列表在相同的位置有一个特定的元素,则返回True。
例如,如果用户想要检查数字1在list1和list2中是否处于相同的位置,他们可以输入1,程序将检查1在两个列表中是否处于相同的位置。
我试过了:
for i in range(len(list1)):
if list1[i] == list2[i]:
return True
else:
return False这个代码的问题是它适用于所有数字,而不仅仅是一个特定的数字。
发布于 2021-01-06 06:16:30
好的,下面是一个简单的解决方案:
list1 = [0, 0, 0, 1, 0]
list2 = [5, 4, 3, 1, 10]
def check_item(item, l1, l2):
# iterate trough the items of l1, l2 simultaneously
for i1, i2 in zip(l1, l2):
# check whether the item of list1 is the same as the one in l2 and if they are the same as the targeted item. If so return True
if i1 == i2 == item:
return True
# else return False
return False
print(check_item(5, list1, list2))
print(check_item(1, list1, list2))如果您愿意,您也可以将其单行:
list1 = [0, 0, 0, 1, 0]
list2 = [5, 4, 3, 1, 10]
def check_item(item, l1, l2):
return any(item == i1 == i2 for i1, i2 in zip(l1, l2))
print(check_item(5, list1, list2))
print(check_item(1, list1, list2))发布于 2021-01-06 06:17:49
您可以像这样使用zip和any函数:
x = 1
list1 = [3,2,1,5,4]
list2 = [5,6,1,7,8]
list3 = [1,3,4,5,6]
list4 = [9,8,7,6,5]
list5 = [9,1,1,6,5]
print(any(a==b==x for a,b in zip(list1,list2))) # True
print(any(a==b==x for a,b in zip(list1,list3))) # False
print(any(a==b==x for a,b in zip(list1,list4))) # False
print(any(a==b==x for a,b in zip(list1,list5))) # Truehttps://stackoverflow.com/questions/65587273
复制相似问题