简体   繁体   English

比较两个列表的真假

[英]Comparing two lists for true and false

for a program I'm writing, I have two lists at the end that I need to compare. 对于我正在编写的程序,最后需要比较两个列表。 They won't be in order, but here's the tricky part. 他们不会井井有条,但这是棘手的部分。 At the end the first list may have more items than the second list. 最后,第一个列表可能比第二个列表具有更多的项目。 But as long as the first list has the required items defined in the second list, the function would return a true value. 但是,只要第一个列表具有在第二个列表中定义的必需项,该函数将返回一个真值。 I tried set lists, but that's more for intersection, which is not what I'm looking for. 我尝试了设置列表,但对于交集来说更多,这不是我想要的。 This is the code I have so far: 这是我到目前为止的代码:

this is the default player inventory, which is added to throughout the game. 这是默认的玩家库存,已添加到整个游戏中。

pla_back = ["Combat Knife","Flares","Compass"]

this is the block of code that compares the two lists. 这是比较两个列表的代码块。 I tried to use in, but it doesn't work. 我尝试用在,但不起作用。

acceptItem = ["Combat Knife","Flares","Compass","silver bar","a cloth","a stick","some rope"]
    if acceptItem in pla_back:
        placeholder
    else:
        placeholder

If someone could help me with this, I would very much appreciate it. 如果有人可以帮助我,我将非常感谢。 I feel like the answer is right on the tip of my toungue, but I just can't figure it out. 我觉得答案就在我的舌头上,但是我只是想不通。

if set(pla_back) >= set(acceptItem):
    print 'Player has the required items'
else:
    print "Player doesn't have the required items"

If my interpretation is correct, you want to see if pla_back contains all the elements in acceptItem . 如果我的理解是正确的,你想看看pla_back包含的所有元素acceptItem So it could have more but as long as it has each element in acceptItem it should return true. 因此它可以有更多,但是只要它在acceptItem具有每个元素,它就应该返回true。

Here >= means 'is superset' >=表示'是超集'

s.issuperset(t)     s >= t      test whether every element in t is in s

So we're checking if every element in acceptItem appears in pla_back 因此,我们正在检查acceptItem中的每个元素acceptItem出现在pla_back

You should make at acceptItem a set. 您应该在acceptItem设置一个集合。 Then you can do 那你可以做

>>> acceptItem = {"Combat Knife","Flares","Compass","silver bar","a cloth","a stick","some rope"}
>>> pla_back = ["Combat Knife","Flares","Compass"]
>>> all(item in acceptItem for item in pla_back)
True

(This also works if acceptItem remains a list, but set lookup is much faster). (如果acceptItem仍然是列表,但是设置查找要快得多,这也可以使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM