How to find the sum of elements in nested list? - python

Below is the given list:
x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]
What I need here is the sum of numbers of each nested list in a different list.
For e.g [162,163,.....]

>>> x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]
>>> y = [sum(i) for i in x]
>>> y
[162, 163, 165, 165, 167, 168, 170, 172, 173, 175]

You can simply do :
x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]
print(list(map(sum,x)))
output:
[162, 163, 165, 165, 167, 168, 170, 172, 173, 175]

Just loop through the items.
First you loop through the internal lists:
for lst in x:
Then you sum the items in the list using the sum method:
total = sum(lst)
Together it looks like this:
new_list = list()
for lst in x:
lst = sum(lst)
new_list.append(total)
print(new_list)
Hope this helps.
Edit: I haven't used the sum method before. Which is why the two downvotes despite the program working fine.

Related

How to sum every element in a list with the previous one?

I would like to receive the following result,
Example:
list1 = [145, 100, 125, 134, 556]
with the output being a new list with the sum results like this:
list2 = [145, 245, 225, 259, 690]
You can also use the zip trick:
>>> list(map(sum, zip(list1, [0]+list1)))
[145, 245, 225, 259, 690]
If you don't mind getting a little bit esoteric, this can be done in a single comprehension without copying the original list:
In [14]: list_1 = [145, 100, 125, 134, 556]
...: b = 0
...: list_2 = [b + (b := a) for a in list_1]
...: list_2
Out[14]: [145, 245, 225, 259, 690]
This is similar to Selcuk's answer but may be a little simpler:
list2 = [a + b for a, b in zip(list1, [0]+list1)]
Or if you don't want to use zip;
list2 = [
list1[i] + (list1[i-1] if i > 0 else 0)
for i in range(len(list1))
]
I suggest using list comprehension for this.
list1 = [145,100,125,134,556]
newLst = [list1[0]]+[sum([list1[i],list1[i-1]]) for i in range(1,len(list1))]
output
[145, 245, 225, 259, 690]
My two cents
list1 = [145,100,125,134,556]
list2 = [val if not idx else val + list1[idx - 1] for idx, val in enumerate(list1)]
I didn't come up with a list comprehension idea.
But if you wanna brute force, it'll be:
list1 = [145, 100, 125, 134, 556]
list2 = [list1[0]]
for i in range(1, len(list1)):
list2.append(list1[i] + list1[i-1])
print(list2)
And you can get
[145, 245, 225, 259, 690]
Python to the old school style!. I have created this function that takes as parameter a list and return a new list with the previous element summed. I hope can help you
def sum_list(list_numbers):
index = 0
list2 = [list_numbers[index]]
while index < (len(list_numbers) - 1):
item = list_numbers[index] + list_numbers[index + 1]
list2.append(item)
index += 1
return list2
print(sum_list(list1))
Output:
[145, 245, 225, 259, 690]
Edit: I wanted to challenge myself using a recursion approach. Maybe it's not the best approach but is here:
list2 = []
def sum_list_recursion(first_element, list_numbers, max_length):
if len(list_numbers) == 0:
return list2
elif len(list_numbers) == max_length:
list2.append(first_element)
next_element = list_numbers[0]
list_numbers = list_numbers[1:]
else:
next_element = list_numbers[0]
list_numbers = list_numbers[1:]
list2.append((first_element + next_element))
sum_list_recursion(next_element, list_numbers, max_length)
sum_list_recursion(list1[0], list1, len(list1))
print(list2)
Output:
[145, 245, 225, 259, 690]

How to append two-dimensional python list without for loop?

Let's suppose that I have 3 python two-dimensional lists (data_1, data_2, data_3) of 10x5 dimensions. I want to make one list (all_data) from them with 30x5 dimensions. For now, I am doing this by applying the following:
data_1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ..., [46, 47, 48, 49, 50]]
data_2 = [[101, 102, 103, 104, 105], [106, 107, 108, 109, 110], ..., [146, 147, 148, 149, 150]]
data_3 = [[201, 202, 203, 204, 205], [206, 207, 208, 209, 210], ..., [246, 247, 248, 249, 250]]
all_data = []
for index, item in enumerate(data_1):
all_data.append(item)
for index, item in enumerate(data_2):
all_data.append(item)
for index, item in enumerate(data_3):
all_data.append(item)
If I simply do something like this:
all_data.append(data_1)
all_data.append(data_2)
all_data.append(data_3)
then I get a list of 3x10x5 which is not what I want.
So can I create a 30x5 list by appending three 10x5 lists without using any for loop?
You can just extend your list.
data = []
data.extend(d1)
data.extend(d2)
data.extend(d3)
Simply write:
all_data = data_1 + data_2 + data_3
If you want to merge all the corresponding sublists of these lists, you can write:
# function that merges all sublists in single list
def flatten(l):
return [el for subl in l for el in subl]
# zipped - is a list of tuples of corresponding items (our deep sublists) of all the lists
zipped = zip(data_1, data_3, data_3)
# merge tuples to get single list of rearranges sublists
all_data = flatten(zipped)
How about:
all_data = data_1 + data_2 + data_3
This should work:
data=[]
data[len(data):] = data1
data[len(data):] = data2
data[len(data):] = data3
In case you don't mind it being lazy, you could also do
import itertools
all_data = itertools.chain(data1, data2, data3)

Looping over a list and saving elements that meet a condition to a new list

I'm trying to loop over a list and save some elements to a new list: the ones that are at more than 50 greater than the previous value. My current code saves only the first value. I want [0, 76, 176, 262, 349].
list = [0, 76, 91, 99, 176, 192, 262, 290, 349]
new_list = []
for i in list:
if ((i+1)-i) > 50:
new_list.extend([i])
Solution
What I want is to save the values 0, 76, 176, 262, and 349.
So it sounds like you want to iterate over the list, and if the current element is greater than its preceding element by 50 then save it to the list and repeat. This solution assumes the original list is sorted. Let's turn this into some code.
lst = [0, 76, 91, 99, 176, 192, 262, 290, 349]
new_lst = []
for i, num in enumerate(lst):
if i == 0 or num - lst[i-1] > 50:
new_lst.append(num)
print(new_lst)
# [0, 76, 176, 262, 349]
The interesting part here is the conditional within the loop:
if i == 0 or num - lst[i-1] > 50:
The first part considers if we're at the first element, in which case I assume you want to add the element no matter what. Otherwise, get the difference between our current element and the previous element in the original list, and check if the difference is greater than 50. In both cases, we want to append the element to the list (hence the or).
Notes
You should avoid using list as a variable so you don't shadow the built-in Python type.
lst.extend([num]) is better written as lst.append(num).
enumerate(lst) allows you to easily get both the index and value of each element in a list (or any iterable).
The statement if ((i+1)-i) > 50 will always evaluate to if (1 > 50) which is false. You're looking for the next element in list, but i is simply the value of the current element. Try something like the tee() function in the itertools library to get multiple values, or something like
list = [0, 76, 91, 99, 176, 192, 262, 290, 349]
new_list = []
for i in range(len(list)):
print (i, list[i])
if i == 0 or (list[i] - list[i-1]) > 50:
new_list.append(list[i])
Keep in mind, I didn't add any checks for whether there is an i + 1 element, so you may need to do some error handling.
EDIT
This is my final edit. I would like to thank #Prune for enforcing standards :)
First, the code in PyCharm:
Second, the console output:
my solution
l = [0, 76, 91, 99, 176, 192, 262, 290, 349]
o = list(l[0]) + [a for a, b in zip(l[1:], l[:-1]) if a - b - 50 > 0]
output: [0, 76, 176, 262, 349]
for i in range(len(list)-1):
if (list[i+1]-list[i]) > 50:
new_list.append(list[i])
if list[-1] - new_list[-1] > 50:
new_list.append(list[-1]) #for the last element of list
Of course, the code can be made better. But this should work.
You can put a condition inside a list comprehension.
Also, do not give a variable the same name (list) as a built-in type.
my_list = [0, 76, 91, 99, 176, 192, 262, 290, 349]
# Start with the first element;
# then grab each element more than 50 greater than the previous one.
new_list = [my_list[0]]
new_list.extend([my_list[i] for i in range(1, len(my_list))
if my_list[i] - my_list[i-1] > 50])
print(new_list)
Output:
[0, 76, 176, 262, 349]

appending list of numbers to new list python

This is kind of hard to describe so I'll show it mainly in code. I'm taking a List of a List of numbers and appending it to a masterList.
The first list in master list would be the first element of each list. I would insert 0 in it's appropriate index in the master list. Then I would move on to the next list. I would choose the first element of the 2nd list and append it to the second list in the master list, since it's index would be 1, I would insert 0 to the first index of that list. This is WAY confusing, please comment back if you have any questions about it. I'll answer back fast. This is really bugging me.
ex:
L = [[], [346], [113, 240], [2974, 1520, 684], [169, 1867, 41, 5795]]
What i want is this:
[[0,346,113,2974,169],[346,0,240,1520,1867],[113,240,0,684,41],[2974,1520,684,0,5795],[169,1867,41,5795,0]]
IIUC, you want something like
>>> L = [[], [346], [113, 240], [2974, 1520, 684], [169, 1867, 41, 5795]]
>>> [x+[0]+[L[j][i] for j in range(i+1, len(L))] for i, x in enumerate(L)]
[[0, 346, 113, 2974, 169], [346, 0, 240, 1520, 1867],
[113, 240, 0, 684, 41], [2974, 1520, 684, 0, 5795],
[169, 1867, 41, 5795, 0]]
which might be easier to read in expanded form:
combined = []
for i, x in enumerate(L):
newlist = x + [0]
for j in range(i+1, len(L)):
newlist.append(L[j][i])
combined.append(newlist)

python - get item number from list

I just asked the following question:
Python - find integer closest to 0 in list
The best answer was to use: min(lst, key=abs).
That code returns the item from the list.
How do I get the item number from the list? (i.e. 2 instead of -18)
You'd need to augment your list with indices:
min(enumerate(lst), key=lambda x: abs(x[1]))
It'll return the index and closest-to-zero value, use [0] if you only need the index.
On your example:
>>> example = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
>>> min(enumerate(example), key=lambda x: abs(x[1]))
(2, -18)
>>> min(enumerate(example), key=lambda x: abs(x[1]))[0]
2
This is very efficient (worst-case O(n)); you can use example.index(min(example, key=abs)) as well, but that has to go through the list twice in the worst case (O(2n)).
>>> lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
>>> lst.index(min(lst, key=abs))
2
Try:
lst.index(min(lst, key=abs))
One way is after finding the integer you want to find, you can use "index"...
result = min(lst, key=abs)
index = lst.index(result)
print(index) # prints 2

Categories

Resources