通过后缀组合列表元素 [英] Combine list elements by suffix

查看:89
本文介绍了通过后缀组合列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个带后缀的列表:

Given two lists with suffixes:

l1 = ['C_1', 'B_1', 'A']
l2 = ['B_2', 'C_2', 'D']

我想这样合并它们:

['C_1', 'C_2', 'B_1', 'B_2', 'A', 'D']

元素应与l1组合为锚.这意味着,如果C_*中的C_*B_*之前,则在输出中将保留相同的顺序.此外,具有相同前缀C_*的元素将按后缀的升序分组在一起.带有后缀的元素按照它们出现的顺序放置,如您在上面看到的那样.

Elements are to be combined with l1 as the anchor. This means, if C_* comes before B_* in l1, the same ordering will be preserved in the output. Furthermore, elements with the same prefix C_* will be grouped together, in increasing order of suffix. Elements with a suffix are placed in the order in which they appear, as you see above.

您可以假定l1中的所有元素都具有后缀_1,而l2中的所有元素都具有后缀_2.

You can assume that all elements in l1 have suffix _1, and all elements in l2 have suffix _2.

我已经尝试过了:

from collections import OrderedDict
from itertools import chain

o = OrderedDict()
for x in l1 + l2:
    o.setdefault(x.split('_')[0], []).append(x) 

result = list(chain.from_iterable(o.values()))

哪个有效,但想知道是否还有其他更简洁的方法.

Which works, but was wondering if there were any more succinct ways of doing this.

后缀只是该元素出现所在列表的一个代表.假设我有l1中的C_1l2中的C_2,然后根据C_*中的哪个出现C_*元素c0>,它位于最终列表中的l2中.(因此,它是... C_1, C_2...).

The suffix is just a stand in for which list that element appears in. Say I have C_1 from l1, and C_2 from l2, then C_* elements appear based on which was in l1 and which was in l2, in the final list (so, it'd be ... C_1, C_2...).

此外,l1l2中的所有元素彼此都是唯一的.希望有帮助.

Furthermore, all elements in l1 and l2 are unique wrt each other and themselves. Hope that helps.

推荐答案

Alex答案很短,但使用了O(n)复杂度的list.index.

Alex answer is short, but uses list.index which has O(n) complexity.

我建议做一个小改动,以构建p作为字典,反转迭代以模拟index的工作方式(当出现多于1个时,返回其他最后的索引).

I would suggest a small adaptation with building p as a dictionary, reversing the iteration to emulate how index works (else last indexes are returned when there are more than 1 occurrence).

在这种情况下,排序键功能改为使用dict查找,速度更快:

In that case, the sort key function uses dict lookup instead, much faster:

l1 = ['C_1', 'B_1', 'A']
l2 = ['B_2', 'C_2', 'D']

p = {s[0]:i for i,s in reversed(list(enumerate(l1 + l2)))}
print(sorted(l1 + l2, key=lambda x: (p[x[0]], x)))

这篇关于通过后缀组合列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆