首页 > 解决方案 > 使用 python 或 awk 查找具有特定后缀的所有核心元素

问题描述

python列表格式:

list1=['a', 'a','b', 'b','c','c','c','d']

list2=['a_1_p', 'a_2_p', 'b_1', 'b_2_p', 'c_1', 'c_2', 'c_3','d_3_p']

输出1:

["a","d"]

选项卡格式(尝试使用 awk)

a_1_p a
a_2_p a
b_1   b
b_2_p b
c_1   c
c_2   c
c_3   c
d_3_p d

输出:

a_1_p a
a_2_p a
d_3_p d

我想在list2中用“_p”提取核心元素(在list1中)。注意:这些核心元素必须在list2中都包含“_p”,在我的例子中,“b”不满足条件。

这是我的解决方案:

c=[]
result=[]
for i in set(list1):
    c.append({i:[n for n in list2 if n.startswith(i)]})

for n in c:
    lst=list(n.values())[0]
    if all(x.endswith("_p") for x in lst):
        result.append(list(n.keys())[0])

输出:

['a', 'd']

相当多的代码。

有没有更容易的“AWK”方式?

非常感谢您提供的任何建议!

标签: pythonawk

解决方案


您可以对 list1 的元素使用一个集合,从中减去 list1 中在 list2 中具有不符合对应关系的项目:

list1=['a', 'a','b', 'b','c','c','c','d']
list2=['a_1_p', 'a_2_p', 'b_1', 'b_2_p', 'c_1', 'c_2', 'c_3','d_3_p']

matches = set(list1).difference( c for c,e in zip(list1,list2) if not(e.startswith(c) and e.endswith("_p")) )
print(matches)
# {'d', 'a'}

推荐阅读