adding elements of a list of lists [duplicate] - python

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 9 years ago.
A function named add_r that takes a list as argument and adds all numeric values in
all levels of the provided list. Assume that the input list will always be a list of numbers or sub-lists that may contain further sub-lists and/or numbers.
For example, add_r( [[1, 2], [3], [[4, 5, 6], [7, 8, [9, 10]]]]) should return 55. Take into
account that the input list provided as argument to the function can contain sublists at any depth.

Use a recursive function:
from collections import Iterable
def add_r(lis):
for x in lis:
if isinstance(x, Iterable):
for y in add_r(x):
yield y
else:
yield x
>>> lis = [[1, 2], [3], [[4, 5, 6], [7, 8, [9, 10]]]]
>>> sum(add_r(lis))
55
On py2.x you can also use compiler.ast.flatten:
>>> from compiler.ast import flatten
>>> sum(flatten(lis))
55

Related

How to count number of elements of each sublist in a list and return a new list [duplicate]

This question already has answers here:
Python find list lengths in a sublist
(7 answers)
Closed 10 months ago.
This is the list that I have:
a = [[1, 2, 3], [3, 0, 6, 4], [4, 2, 3, 6, 8]]
I would like to count the number of elements of each sublist in the list and return a new list to have the desired output of
a = [3, 4, 5]
I know how to get the total number of elements in the list with lists but not sure how to get the number of elements in each sublist...
You can try this code: a = [len(ele) for ele in a]

How to turn lists of lists into integers [duplicate]

This question already has answers here:
List of list, converting all strings to int, Python 3
(4 answers)
Closed 11 months ago.
I know how to transform a single list of strings into integers...
But how do I transform lists of lists (strings) from into integers
I want this list:
['[1,', '3]', '[3,', '4]', '[5,', '8]', '[6,', '10]']
become a list of integers:
[1, 3], [3, 4], [5, 8], [6, 10]
The main problem with your example data, is that there's no commas between lists, you could do something like this to parse the different lists:
>>> parsed = re.findall(r'\[.+?\]', ''.join(data))
['[1,3]', '[3,4]', '[5,8]', '[6,10]']
>>> ast.literal_eval(', '.join(parsed))
([1, 3], [3, 4], [5, 8], [6, 10])

how can i access specific ints from lists and add them to a new list? [duplicate]

This question already has answers here:
Matrix Transpose in Python [duplicate]
(19 answers)
Closed 1 year ago.
new to python so i am writing this code that takes lists and returns a transpose version of it for example
mat = [[1,2],[3,4],[5,6]]
mat_T = mat_transpose(mat)
print(mat)
# [[1, 2], [3, 4], [5, 6]]
print(mat_T)
# [[1, 3, 5], [2, 4, 6]]
this is an example of a correct output
now how do i access the ints in a way that i can add them to a new list like the ints 1 3 5 are all in different lists but i need the in the same list and so are the ints 2 4 6 and so on if there were more ints in more lists
You don't need to access the individual values, use zip to iterate over the transposed values and map+list to convert each transposed subarray into list:
mat = [[1,2],[3,4],[5,6]]
mat_T = list(map(list, zip(*mat)))
mat_T
output:
>>> mat_T
[[1, 3, 5], [2, 4, 6]]

How to create one single array with multiple array in python? [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 3 years ago.
I have this code to make an array that shows the index of "frq_peak" that contains each elements of "F".
a =[]
for i in range(len(F)):
if i == 0:
a.append(np.where(frq_peak[6] == F[i]))
elif F[i] != F[i-1]:
a.append(np.where(frq_peak[6] == F[i]))
a
the problem is that "a" become a combination of multiple array but I want to have just one. what should I do?
You can use this code, where your array is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:
from functools import reduce
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
singleArray = reduce(lambda x, y: x+y, arr)

Sort nested list by second value [duplicate]

This question already has answers here:
How to sort a list of lists by a specific index of the inner list?
(12 answers)
Understanding slicing
(38 answers)
Closed 3 years ago.
Input : [[0, 2], [1, 4], [2, 6]]
Description : I need to print two lists with greater value by comparing the element in the 2nd place.
Expected Output: [[1, 4], [2, 6]]
You can use sorted and specify in the key argument that you want to sort each sublist by the second element using operator.itemgetter. Then slice the returned list to select the two last sublists:
l = [[0, 2], [1, 4], [2, 6]]
from operator import itemgetter
sorted(l, key=itemgetter(1))[-2:]
Output
[[1, 4], [2, 6]]

Categories