我目前正在尝试在许多其他项目的列表中创建一些不需要的项目的黑名单。
我目前有一个非常丑陋的条件语句,它可以正常工作,但我觉得添加它看起来很乏味,而且看起来很糟糕。我必须手动添加它,我发现这是一个问题,因为我想根据我的代码中的函数添加到黑名单,所以手动添加将不再足够。
我想" NEW"在所需项目的标题中,以下所有条件都是"而不是黑名单",这似乎非常重复。
if "NEW" in lst[i][0] and "Pears" not in lst[i][0] and "Strawberries" not in lst[i][0] and "Oranges" not in lst[i][0] and "Cherries" not in lst[i][0] and "Plums" not in lst[i][0] and "Nectarines" not in lst[i][0] and "raspberries" not in lst[i][0] and "Apples" not in lst[i][0]:
我想找到一种方法来简单地创建一个黑名单列表,并且如果在另一个列表中找不到黑名单中的任何项目,则继续python。
我已尝试创建黑名单并尝试:
lst = ['Broccoli', 'Chicken', 'Oranges', 'Apples', 'Squash', ' Salmon']
blacklist = ['Pears', 'Strawberries', 'Oranges']
#My actual lists are much longer
for i in range(len(lst)):
for blacklisteditem in blacklist:
if blacklisteditem in lst[i]:
print("This item is not blacklisted, proceeding..")
else:
print("This item was blacklisted")
但是这会回来:
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item is not blacklisted, proceeding..
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
This item was blacklisted
显然不是这里的目标。必须有一些我忽略的解决方案,任何人都可以帮助我吗? 我只是想应用&#34的逻辑;如果x不在lst:",但我希望x是多个项目,最好是列表中的项目,或者我可以附加的字符串?
我基本上需要能够以某种方式附加到此黑名单,而不必手动编辑脚本,因为我希望我的程序能够添加其他条目。如果这涉及以某种方式附加长而丑陋的条件,那么只要它有效就可以了。
答案 0 :(得分:5)
将您的黑名单设为一个集合,并测试您的列表是否没有交集(该集合不相交):
blacklist = {'Pears', 'Strawberries', 'Oranges'}
if blacklist.isdisjoint(lst):
print("This item is not blacklisted, proceeding..")
else:
print("This item was blacklisted")
set.isdisjoint()
method仅在没有共同元素的情况下才返回True
:
>>> lst = ['Broccoli', 'Chicken', 'Oranges', 'Apples', 'Squash', ' Salmon']
>>> blacklist = {'Pears', 'Strawberries', 'Oranges'}
>>> blacklist.isdisjoint(lst)
False
>>> blacklist.isdisjoint(['Broccoli', 'Chicken', 'Apples', 'Squash', ' Salmon'])
True
您的尝试不会等到所有列入黑名单的物品都经过测试;您打印您测试的每个元素。你需要等到你的for循环完成后再得出结论:blacklist
个元素都没有出现。