python - 使用 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”方式?
非常感谢您提供的任何建议!
解决方案
您可以对 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'}
推荐阅读
- javascript - 如何创建有条件的缓和?
- php - 如何渲染一维和多维数组
- vb.net - 问题是从字符串到类型日期的转换无效
- python - python中的“self”参数是什么意思?
- flutter - 为颤振条码扫描添加新的覆盖 (barcode_scan)
- python - 使用表的两个不同列的 Python 函数
- asp.net-core - 如何在没有提交剃须刀的情况下获得控件值?
- r - 是否有 R 代码可以删除具有两个 - 三个不同列条件的相同 ID 的重复事件?
- python-3.x - 如何通过filestack python批量上传
- ruby-on-rails - 在 Dokku 上部署 Rails 时出错 - 在 Digital Ocean 上