【问题标题】:How to build a third list by comparing two other list with string matching. [duplicate]如何通过将其他两个列表与字符串匹配进行比较来构建第三个列表。 [复制]
【发布时间】:2017-07-04 07:12:21
【问题描述】:

我的问题的答案可能就在这里,但我找不到。

我有两个列表:

['batman','superman','spiderman',]
['batman','ironman','superman','flash','wonderwoman']

我想比较两个列表并将匹配的元素作为第三个列表返回:

['batman','superman']

我只找到了这个解决方案:

list=['a cat','a dog','a yacht']
string='a cat'
if string in list:
  print 'found a cat!'

但这只是字符串和列表之间的比较……

【问题讨论】:

  • 拜托,你没有搜索那么多。有太多的重复。 one-liner:set(list1).intersection(list2) 是一个。

标签: python list string-matching


【解决方案1】:

使用intersection

l1 = ['batman','superman','spiderman',]
l2 = ['batman','ironman','superman','flash','wonderwoman']

print(set(l1).intersection(set(l2)))
#set(['batman', 'superman'])

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 1970-01-01
    • 2014-02-21
    • 2017-10-28
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多