如何合并 python 列表并根据第一个元素在列表中创建列表?
How to combine python list and create list within a list based on first element?
我正在尝试根据嵌套列表的第一个元素编译一个 python 列表。但是我不确定这样做的正确方法是什么。
我有这个嵌套列表。
list1 = [[1, a, b, c], [2, b, c, d], [2, b, d, e], [1, c, a, d]]
我正在尝试获得这样的输出。
output_list = [[1, [a, b, c], [c, a, d]], [2, [b, c, d], [b, d, e]]]
用defaultdict累加,最后用list comprehension:
>>> list1 = [[1, 'a', 'b', 'c'], [2, 'b', 'c', 'd'], [2, 'b', 'd', 'e'], [1, 'c', 'a', 'd']]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for first, *rest in list1:
... d[first].append(rest)
...
>>> [[first, *rest] for first, rest in d.items()]
[[1, ['a', 'b', 'c'], ['c', 'a', 'd']], [2, ['b', 'c', 'd'], ['b', 'd', 'e']]]
list1 = [[1, "a", 'b', 'c'], [2, 'b', 'c', "d"], [2, 'b', 'd', 'e'], [1, 'c', 'a', 'd']]
firstList = []
output_list = []
for i, list in enumerate(list1):
if list[0] not in firstList:
firstList.append(list[0])
anotherList = []
for j in range(1, len(list)):
anotherList.append(list[j])
bList = [list[0], anotherList]
output_list.append(bList)
else:
place = firstList.index(list[0])
anotherList = []
for j in range(1, len(list)):
anotherList.append(list[j])
output_list[place].append(anotherList)
print(output_list)
>>>[[1, ['a', 'b', 'c'], ['c', 'a', 'd']], [2, ['b', 'c', 'd'], ['b', 'd', 'e']]]
我正在尝试根据嵌套列表的第一个元素编译一个 python 列表。但是我不确定这样做的正确方法是什么。
我有这个嵌套列表。
list1 = [[1, a, b, c], [2, b, c, d], [2, b, d, e], [1, c, a, d]]
我正在尝试获得这样的输出。
output_list = [[1, [a, b, c], [c, a, d]], [2, [b, c, d], [b, d, e]]]
用defaultdict累加,最后用list comprehension:
>>> list1 = [[1, 'a', 'b', 'c'], [2, 'b', 'c', 'd'], [2, 'b', 'd', 'e'], [1, 'c', 'a', 'd']]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for first, *rest in list1:
... d[first].append(rest)
...
>>> [[first, *rest] for first, rest in d.items()]
[[1, ['a', 'b', 'c'], ['c', 'a', 'd']], [2, ['b', 'c', 'd'], ['b', 'd', 'e']]]
list1 = [[1, "a", 'b', 'c'], [2, 'b', 'c', "d"], [2, 'b', 'd', 'e'], [1, 'c', 'a', 'd']]
firstList = []
output_list = []
for i, list in enumerate(list1):
if list[0] not in firstList:
firstList.append(list[0])
anotherList = []
for j in range(1, len(list)):
anotherList.append(list[j])
bList = [list[0], anotherList]
output_list.append(bList)
else:
place = firstList.index(list[0])
anotherList = []
for j in range(1, len(list)):
anotherList.append(list[j])
output_list[place].append(anotherList)
print(output_list)
>>>[[1, ['a', 'b', 'c'], ['c', 'a', 'd']], [2, ['b', 'c', 'd'], ['b', 'd', 'e']]]