在python中按另一个列表对多维列表排序

2024-10-02 18:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的清单。你知道吗

第一:(苹果、榴莲、樱桃、鸡蛋、香蕉)

第二:((香蕉,b1,b2,b3,b4), (榴莲,d1,d2,d3,d4), (苹果,a1,a2,a3,a4), (蛋,e1,e2,e3,e4), (樱桃、c1、c2、c3、c4)

我想用第一张单子排列第二张单子。 所以我期待这个。你知道吗

     ((apple,a1,a2,a3,a4),
      (durian,d1,d2,d3,d4),
      (cherry,c1,c2,c3,c4),
      (egg,e1,e2,e3,e4),
      (banana,b1,b2,b3,b4))

请告诉我怎么做。 谢谢。你知道吗


Tags: 苹果a2a1b2a3b1b3d2
3条回答
In [25]: d = {L[0]:list(L[1:]) for L in second}

In [26]: answer = [[k]+d[k] for k in first]

In [27]: answer
Out[27]: 
[['apple', 'a1', 'a2', 'a3', 'a4'],
 ['durian', 'd1', 'd2', 'd3', 'd4'],
 ['cherry', 'c1', 'c2', 'c3', 'c4'],
 ['egg', 'e1', 'e2', 'e3', 'e4'],
 ['banana', 'b1', 'b2', 'b3', 'b4']]

用字典怎么样?你可以试试这个:

# first : (apple, durian, cherry, egg, banana)
# second : ((banana,b1,b2,b3,b4), (durian,d1,d2,d3,d4), (apple,a1,a2,a3,a4), (egg,e1,e2,e3,e4), (cherry,c1,c2,c3,c4))

d = {}
for lst in second:
    d[lst[0]] = lst

result = []
for item in first:
    # you shall ensure that key `item` exists in `d`
    result.append(d[item])

首先,这些是元组,其次,你给出的所有示例实际上都不是字符串,所以我为你做了这些。你知道吗

现在让我们先将其转换为字典:

data = [('banana','b1','b2','b3','b4'),
        ('durian','d1','d2','d3','d4'),
        ('apple','a1','a2','a3','a4'),
        ('egg','e1','e2','e3','e4'),
        ('cherry','c1','c2','c3','c4')]

data = {t[0]:t for t in data}  # make dictionary with dictionary comprehension.

不,我们有选择器:

selector = ['apple', 'durian', 'cherry', 'egg', 'banana']

然后我们排序并创建列表:

results = [data[key] for key in selector]  # order result by selector

回答:

[('apple', 'a1', 'a2', 'a3', 'a4'), 
 ('durian', 'd1', 'd2', 'd3', 'd4'), 
 ('cherry', 'c1', 'c2', 'c3', 'c4'), 
 ('egg', 'e1', 'e2', 'e3', 'e4'), 
 ('banana', 'b1', 'b2', 'b3', 'b4')]

相关问题 更多 >