检查列表是否包含除“ apples”和“ oranges”以外的其他字符串

时间:2019-03-04 07:25:46

标签: python list

如何知道python中的列表是否包含除'apples''oranges'之外的其他元素。

fruits = ['apples', 'oranges']

现在,如果列表结果包含任何其他字符串,则假定:

fruits = ['apples', 'oranges', grapes'] 要么 fruits = ['oranges', grapes']

如何检查?

6 个答案:

答案 0 :(得分:1)

尝试以下代码:

fruits = ['apples', 'oranges', 'grapes']

for i in fruits:
    if i not in ['apples','oranges']:
       print i  # Mismatched values will be printed

输出:

grapes

答案 1 :(得分:1)

您可以使用set object

target = ['apples', 'oranges']
fruits = ['apples', 'oranges', 'grapes', 'whatever']

set(fruits) - set(target)
#=> {'whatever', 'grapes'}

答案 2 :(得分:0)

尝试一下:

nlr <- nls(formula = valuerange1 ~ exp(m1*temp), data = list(temp,valuerange1), start= list(m1=0.001))

输出:

f = ['apples', 'oranges', 'grapes']
any(x not in ['apples', 'oranges'] for x in f)

答案 3 :(得分:0)

如果您想要另一个列表,其中项目与'apples''oranges'分开,请尝试以下操作:

fruits = [i for i in fruits if i not in ['apples', 'oranges']]

答案 4 :(得分:0)

您可以使用filter列表:

fruits_list = ['apples', 'oranges', 'mangoes']
filter_list =  ['apples', 'oranges']

print([x for x in fruits_list if x not in filter_list])

输出

['mangoes']

答案 5 :(得分:0)

如果列表中有多个“橙色”,您期望什么行为? 我考虑忽略所有加倍元素。

一旦从检查列表中找到其他任何元素,该函数应停止检查。

def check_if_there_something_else(original_list: list, checking_for: list):
    for fruit in original_list:
        if fruit not in checking_for:
            return True
    return False

original_list = ['oranges', 'oranges', 'grapes']
checking_for = ['oranges', 'grapes']
print(check_if_there_something_else(original_list, checking_for))

错误

original_list = ['oranges', 'oranges', 'grapes', 'grapes', 'grapes', 'kiwi']
checking_for = ['oranges', 'grapes']
print(check_if_there_something_else(original_list, checking_for))

您可以通过查找集合之间的差异来进行几乎相同的检查,但是创建两个新对象看起来很多余:

print(any(set(original_list).difference(checking_for)))