【问题标题】:Search through lists in Python to find matches?在 Python 中搜索列表以查找匹配项?
【发布时间】:2017-09-12 12:16:17
【问题描述】:

我有 Python 列表,其中包含各种字符串,例如:

List1 = ["a","b","c","d"]
List2 = ["b","d","e","f"]
List3 = []
List4 = ["d","f","g"]

我需要遍历这些列表,前提是它们不是空白的,并找到所有非空白列表中的项目。在上面的示例中,精确匹配列表将是 ["d"],因为这是唯一出现在所有非空白列表中的项目。 List3 是空白的,因此它不在该列表中也没关系。

【问题讨论】:

  • 输出列表的顺序重要吗?
  • 您“需要密码”?
  • 不,它没有。只要我可以将每个完全匹配的内容附加到它。
  • 你读过How to Ask吗?

标签: python list loops


【解决方案1】:
for thing in list1: # iterate each item, you can check before hand if its not empty
      if len(list2) > 0: # if not empty
         if thing in list2: # in the list 
            # do the same thing for the other lists

类似的东西

【讨论】:

  • if len(list2) > 0: # if not emptyif list2: 会检查它不是一个空列表(这是错误的)。
【解决方案2】:

这里有一些函数式编程之美:

from operator import and_
from functools import reduce

Lists = List1, List2, List3, List4

result = reduce(and_, map(set, filter(None, Lists)))

【讨论】:

  • 顺便说一句,operator-免费版:reduce(set.intersection, map(set, filter(None, Lists)))
  • @timgeb,酷,这样看起来会更好。此外,更少的进口。
  • 另外,这节省了手动将所有列表转换为集合,只有Lists[0]必须是集合。 (我没有计时这是否有任何区别。)
【解决方案3】:

我现在无法对此进行测试,但应该可以使用以下方法:

intersection(set(l) for l in [List1, List2, List3, List4] if l)

它使用 Python 内置的 set 数据类型来进行交集操作。

【讨论】:

  • intersectionset 的方法,不是独立函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 2014-12-16
  • 2020-04-06
  • 1970-01-01
相关资源
最近更新 更多