How to insert list into nested list in python?
Question:
Right now I am practicing List
I am facing a problem of inserting nested list.
for instance; I have a nested list and i want to make another nested.
example
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
output should be:
output = [['a'[1,2],[2,3]], ['b'[3],[4]], ['c'[4],[5]]]
Answers:
Use a dictionary to collect all the sublists with the same string.
from collections import defaultdict
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
output_dict = defaultdict(lambda: [[], []])
for num1, key, num2 in a:
output_dict[key][0].append(num1)
output_dict[key][1].append(num2)
output = [[key, *val] for key, val in output_dict.items()]
output
is
[['a', [1, 2], [2, 3]], ['b', [3], [4]], ['c', [4], [5]]]
You could do this with an list, however, a dictionary is probably better in your use case.
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
dct = {}
for arr in a:
key = arr[1]
del arr[1]
if key not in dct:
dct[key] = [arr]
else:
dct[key].append(arr)
print(dct) # => {'a': [[1, 2], [2, 3]], 'b': [[3, 4]], 'c': [[4, 5]]}
If you need a list, then you can use list comprehension to turn the dictionary into a list
lst = [[key, *dct[key]] for key in dct]
print(lst) # => [['a', [1, 2], [2, 3]], ['b', [3, 4]], ['c', [4, 5]]]
Right now I am practicing List
I am facing a problem of inserting nested list.
for instance; I have a nested list and i want to make another nested.
example
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
output should be:
output = [['a'[1,2],[2,3]], ['b'[3],[4]], ['c'[4],[5]]]
Use a dictionary to collect all the sublists with the same string.
from collections import defaultdict
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
output_dict = defaultdict(lambda: [[], []])
for num1, key, num2 in a:
output_dict[key][0].append(num1)
output_dict[key][1].append(num2)
output = [[key, *val] for key, val in output_dict.items()]
output
is
[['a', [1, 2], [2, 3]], ['b', [3], [4]], ['c', [4], [5]]]
You could do this with an list, however, a dictionary is probably better in your use case.
a = [[1, 'a', 2], [2, 'a', 3], [3, 'b', 4], [4, 'c', 5]]
dct = {}
for arr in a:
key = arr[1]
del arr[1]
if key not in dct:
dct[key] = [arr]
else:
dct[key].append(arr)
print(dct) # => {'a': [[1, 2], [2, 3]], 'b': [[3, 4]], 'c': [[4, 5]]}
If you need a list, then you can use list comprehension to turn the dictionary into a list
lst = [[key, *dct[key]] for key in dct]
print(lst) # => [['a', [1, 2], [2, 3]], ['b', [3, 4]], ['c', [4, 5]]]