根据先前的值添加到列表中 [英] Add to a list based on previous value

查看:51
本文介绍了根据先前的值添加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此列表分组在一起

I am trying to group this list together

示例输入

M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]

输出

[['a',14,7,16],['b',3,15],['c',22,1,5]]

含义是将所有"a"值组合在一起,对于"b","c"等同样适用

Meaning group all the 'a' value together same goes for 'b', 'c' and so on

推荐答案

要获取列表列表(如您的问题所要求的),您可以执行以下操作:

To get a list of lists (like your questions asks for) you can do something like this:

M1 = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
output = {}
for l in M1:
    if l[0] in output.keys():
        output[l[0]].append(l[1:][0])
    else:
        output[l[0]] = l[1:]

# Output is now a dictionary. You can stop here if you're fine with a dictionary, or continue on from here

listOfLists = []
for k, v in output.items():
    listOfLists.append([k, *v])

然后是结果:

>>> print(output)
# {'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}

>>> print(listOfLists)
# [['a', 14, 15, 7, 16], ['b', 3, 15], ['c', 22, 1, 5]]

这篇关于根据先前的值添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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