gpt4 book ai didi

python - 如何检查列表中是否出现两个列表项的任意组合

转载 作者:行者123 更新时间:2023-12-03 00:57:17 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以检查另一个列表中是否存在列表中两个以上项目的任何组合?

list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']

for string in lists:
strings = string.split()
print(strings)

字符串的示例输出:

['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']# this line should identify 'banana', 'soap' and 'veggies'
['maybe', 'there','are','more','sweets','left','later'] # this line should be ignored, because not more than 2 items of the list are in it
['food', 'shopping','is','boring','and','i','hate','mash','with','veggies']# this line should identify 'mash' and 'veggies'

我知道通过使用这段代码,我至少可以检查字符串中是否出现任何元素:

  combinations = any(i in list_1 for i in strings)

最佳答案

您可以使用set intersection并检查结果大小:

s1 = set(list_1)

if len(s1.intersection(strings)) >= 2:
# do stuff

但是,如果同一个项目在字符串中出现两次,这将不会触发,这可能是也可能不是您想要的。在这种情况下,您可以执行以下操作:

if sum(s in s1 for s in strings) >= 2:
# do stuff

关于python - 如何检查列表中是否出现两个列表项的任意组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61519332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com