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

时间:2021-01-10 20:11:42

标签: python list

谁能告诉我编写此逻辑的最短方法是什么?

我有两个列表,分别是 list_onelist_two,其中包含一些字母。如果这两个列表都不包含“B”,我需要打印(真)。我写的代码片段有效,但我很想知道是否有一种 Pythonic 的方式来编写它,而不是在同一行中重复 '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')

提前致谢,任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

好吧,你可以这样做(尽管我认为你的方法是最好的):

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')

答案 1 :(得分:2)

如果 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]))

答案 2 :(得分:1)

我们在 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 ))

答案 3 :(得分:1)

另一种方法是首先将所有列表放入 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()
相关问题