首页 > 解决方案 > 比较python中的两个数组以查看它们是否共享任何值

问题描述

我正在尝试在 python 中创建一个小程序,要求您输入以逗号分隔的车牌列表。

然后它将字符串转换为数组并要求提供第二组车牌(同样,用逗号分隔)。

我想要它做的是,一旦你输入了两组车牌,它应该告诉你是否有匹配的车牌,如果有,它们是什么。我目前有这个

print('Enter the first set of number plates')
print('Make sure to separate each plate with a comma')

nbPlateInput = input('\n')
nbPlates = str(nbplateinput)

if ',' in nbPlates:
    splitPlate = nbPlates.split(',')
elif ',' not in nbPlates:
    print('\nYou did not separate all number plates with a comma')
    exit()

print('\nEnter the second set of number plates')

nbPlateInput2 = input()
nbPlates2 = str(nbPlateInput2)

if ',' in nbPlates:
    splitPlate2 = nbPlates2.split(',')
elif ',' not in nbPlates2:
    print('\nYou did not separate all number plates with a comma')
    exit()

if any(word in splitPlate for word in splitPlate2):
    duplicate = any(word in splitPlate for word in splitPlate2)
    print(duplicate)
else:
    print('No Match')
    exit()

目前,当有匹配时它输出真,当没有匹配时,它输出“不匹配”我希望它输出匹配的车牌

PS。我对python很陌生,如果我的代码有点乱,我很抱歉

编辑:我最后使用了这段代码而不是我的“如果有”语句

intersect = list(set(splitplate) & set(splitplate2))
print(intersect)

这将打印任何相同的值

标签: pythonarrayspython-3.x

解决方案


推荐阅读