【问题标题】:making loop script that needs to remove list elements as it goes thru制作需要删除列表元素的循环脚本
【发布时间】:2019-07-04 10:50:54
【问题描述】:

Python 问题

import fnmatch

list_1 = ['family', 'brother', 'snake', 'famfor']

list_2 = ['a', 'f', 'f', 'm', 'i', 'l', 'y']

match = fnmatch.filter(list_1, 'fa????')

print match

这会给我

>> ['family', 'famfor']

我怎样才能在这个查询中只得到家人? 通过检查 list_2 的有效字母。

【问题讨论】:

  • 这个问题我不清楚。 fnmatch.filter(list_1, 'fa????') 将匹配 list_1 中长度为 6 且前两个字母为 'fa' 的任何字符串。您希望使用list_2 执行什么样的进一步检查?请更好地解释这一点。
  • 这是我尝试做的一种更小的版本。 List_2 是我试图找到的单词的基础。 list_1 中的单词必须只有 list_2 中的字母。所以我必须排除 list_1 中所有包含不在 list_2 中的字母的单词。

标签: python


【解决方案1】:

您可以先将list_2 转换为集合以进行高效查找,然后使用带有条件的列表推导式作为过滤器:

set_2 = set(list_2)
[w for w in list_1 if all(c in set_2 for c in w)]

这会返回:

['family']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2021-12-14
    • 2012-05-26
    相关资源
    最近更新 更多