检查是否至少有一个列表包含特定元素



有人能告诉我写这个逻辑的最短方法是什么吗?

我有两个列表,分别为list_onelist_two,其中包含一些字母。如果这两个列表都不包含"B",我需要打印(True(。我写的这个片段很有效,但我很想知道是否有一种蟒蛇般的方式来写这个,而不是在同一行重复两次"B"。

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']

if 'B' not in list_one and 'B' not in list_two:
print('True')

提前感谢,如有任何帮助,我们将不胜感激。

好吧,你可以做到(尽管我认为你的方式是最好的(:

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']

if 'B' not in (set(list_one) & set(list_two)):
print('True')

或者:

if 'B' not in list_one + list_two:
print('True')

如果all函数更易读,您可以尝试它。

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']
print(all('B' not in current_list for current_list in [list_one, list_two]))

我们在Python中有sets,与列表相比,它们真的很快。

这里是关于集合的一些特征。

  • 集合是无序的
  • 集合元素是唯一的
  • 集合中不允许有重复的元素

因此,您可以在公共集合中搜索项目。

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']
if 'B' not in set(list_one + list_two)
print('True')

奖金:您可以使用extend方法来加速的列表连接

set( list_one.extend( list_two ))

一种不同的方法是先将所有列表放在Pandas DataFrame中:

import pandas as pd
df = pd.DataFrame(list(zip(list_one, list_two)), columns =['l1', 'l2']) 

然后,您可以通过返回True来轻松检查字符B是否不存在。双.any()用于检查行和列:

~df.isin(['B']).any().any()

相关内容

最新更新