In the following code, I am trying to append a list called a to a list of lists b.
a = [5,4]
b = [[4],[3],[8]]
b[2].append(a)
Python outputs
[[4], [3], [8, [5, 4]]]
However, I want the elements to be appended as integers not as a list so b should be [[4], [3], [8, 5, 4]] and then I want to merge the lists so b would be [4, 3, 8, 5, 4]. I want to be able to do this so I can use the sum function to find the sum of b's elements. Does anyone have suggestions regarding how this can be done?
First, you are trying to extend a list, not append to it. Specifically, you want to do
b[2].extend(a)
append()
adds a single element to a list. extend()
adds many elements to a list. extend()
accepts any iterable object, not just lists. But it's most common to pass it a list.
Once you have your desired list-of-lists, eg
[[4], [3], [8, 5, 4]]
then you need to concatenate those lists to get a flat list of ints. You can use sum()
for that -- adding lists is not that different from adding ints.
b = sum(b, [])
The trick here is that you have to pass the initial (empty) value to sum()
, otherwise it tries to add the lists in b
as though they were numbers.
Finally, you can sum the flattened list as you intended:
sum(b)
My suggestion is to use the chain function taken from the itertools builtin package to achieve your goal in a more concise and pythonic way.
Just one line of code is needed:
sum(chain(a, tuple(chain.from_iterable(b))))
If I understood it correctly, you want a list full of integers -not a list with lists of integers-.
Anyways I'll try to give a solution for both of them.
for i in range(len(a)):
b[-1].append(a[i])
Outputs: b = [[4], [3], [8, 5, 4]]
or maybe just every number in one list:
for i in range(len(a)):
b.append([a[i]])
Outputs: b = [[4], [3], [8], [5], [4]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.