list_1 = ['apple', 'banana', 'orange']
list_2 = ['banana', 'kiwi', 'pear', 'apple']
for item in list_1:
if item in list_2:
print(f'{item} is in both lists.')
else:
print(f'{item} is not in the second list.')
输出:
apple is in both lists.
banana is in both lists.
orange is not in the second list.
另一种方法:
list_1 = ['apple', 'banana', 'orange']
list_2 = ['banana', 'kiwi', 'pear', 'apple']
matches = set(list_1) & set(list_2)
non_matches = set(list_1) - set(list_2)
print(f'Matches: {matches}')
print(f'Non-matches: {non_matches}')
输出:
Matches: {'apple', 'banana'}
Non-matches: {'orange'}