返回修改后的列表对的列表

时间:2019-04-26 07:44:09

标签: python

在下面的my_list中使用列表对列表,我如何创建一个新列表,在该列表中,普通element [0]值将具有其相应element [1]值的列表?主列表中元素的顺序无关紧要。

示例

my_list = [['color', 'red'], ['length', 2], ['color', 'blue], ['shape', 'circle'], ['shape', 'square']]

return [['color', ['red', 'blue']], ['shape', ['circle', 'square']], ['length', 2]]

1 个答案:

答案 0 :(得分:2)

如果您不介意按键的顺序,则可能要使用默认字典。

my_list = [['color', 'red'], ['length', 2], ['color', 'blue'], ['shape', 'circle'], ['shape', 'square']]

from collections import defaultdict

d = defaultdict(list)
for sublist in my_list:
    d[sublist[0]].append(sublist[1])
print(d)

如果您绝对希望将其作为您指定的列表

answer = []
for key in d:
    if len(d[key]) == 1:
        answer.append([key, d[key][0]])
    else:
        answer.append([key, d[key]])
print(answer)
相关问题