简体   繁体   English

将列表中的每个元素与另一个列表中的每个元素进行比较

[英]Compare each element in a list with every element in another list

I have two lists, words = ["hello", "how", "hello", "are", "you"] and match = ["hello, "sonic"] . How do I compare in such a way that if the first element in match is the same as the first element in words and (same for second, third etc), then append 'true' to another list?我有两个列表, words = ["hello", "how", "hello", "are", "you"]match = ["hello, "sonic"] 。我该如何比较,如果匹配中的第一个元素与单词中的第一个元素相同并且(第二个,第三个等相同),然后 append 'true'到另一个列表?

So for the above lists, I would want results = ["true", "false", true", "false", "false"] . I currently have the following but this only appends true and never false . I know that it is because the else statement never executes as 'hello' is always in words[] . I know I am quite far off the mark here.所以对于上面的列表,我想要results = ["true", "false", true", "false", "false"] 。我目前有以下内容,但这只会附加true而不会附加false 。我知道它是因为else语句永远不会执行,因为'hello'总是在words[]中。我知道我在这里离题很远。

for i in match:
    if i in words:
        results.append('true')
    else:
        results.append('false')

I hope I explained it well.我希望我解释得很好。

Try using the python "in" syntax:尝试使用 python "in" 语法:

match = ["hello", "sonic"]
words = ["hello", "how", "hello", "are", "you"]
results = [w in match for w in words]

or if you want the strings "true" or "false"或者如果你想要字符串“true”或“false”

results = [str(w in match).lower() for w in words]

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

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