【问题标题】:python: compare two lists and return matches in orderpython:比较两个列表并按顺序返回匹配项
【发布时间】:2014-11-28 14:21:30
【问题描述】:

我有两个长度不等的列表,我想从第一个列表中按顺序比较和提取匹配的值,所以在这个例子中。

a = ['a','s','d','f']
b = ['e','d','y','a','t','v']

预期输出:

['a','d']

我是这样做的,但我忘记了那套不保留顺序!如何在下面编辑我的代码以保留订单。

 set(a).intersection(b)

链接到这个How can I compare two lists in python and return matches

【问题讨论】:

  • 预期输出是什么?
  • 顺序是如何定义的? – _
  • 在“a”中找到的顺序
  • 你会优先订购哪个清单???

标签: python list set


【解决方案1】:
a = ['a','s','d','f']
b = ['e','d','y','a','t','v']
matches=[]
for item_a in a:
    for item_b in b:
        if item_a == item_b:
            matches.append(item_a)
print(matches)

【讨论】:

    【解决方案2】:

    将b 转换为一个集合,然后循环遍历a 的项目并检查它们是否存在于该集合中:

    >>> s = set(b)
    >>> [x for x in a if x in s]
    ['a', 'd']
    

    【讨论】:

      【解决方案3】:

      你需要使用集合:

      >>> a = ['a','s','d','f']
      >>> b = ['e','d','y','a','t','v']
      >>> sorted(set(a) & set(b), key=a.index) # here sorting is done on the index of a
      ['a', 'd']
      

      【讨论】:

      • 如果a = ['a','s','d','a']怎么办?
      • 我希望['a', 'd', 'a'] 但这个问题可能是学术问题。
      【解决方案4】:
      a = ['a','s','d','f']
      b = ['e','d','y','a','t','v']
      st_b = set(b)
      print([ele for ele in a if ele in st_b])
      ['a', 'd']
      

      【讨论】:

        猜你喜欢
        • 2016-12-23
        • 2010-11-26
        • 1970-01-01
        • 2020-12-19
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        相关资源
        最近更新 更多