Add an unknown number of lists by index - python

I need to add every index of an unknown amount of lists together into one list.
An example of what I mean:
list_a = [1,2,3,4,5]
list_b = [2,4,6,8,10]
list_c = [3,6,9,12,15]
def sum_lists():
temp_list = []
for index in range(len(list_a)):
temp_list.append(list_a[index] + list_b[index] + list_c[index])
return temp_list
total = sum_lists()
The expected output of my example code would be:
total = [6,12,18,24,30]
How would I accomplish the summation of an unknown amount of lists, for example 20 lists? I won't have to do this addition over thousands of lists, but I wouldn't know how many lists I have to add initially.
Any help would be greatly appreciated. All of the lists will be of the same length.

Create a list of lists:
In [124]: big_list = [list_a, list_b, list_c]
Now, zip em up and apply sum to each one using map:
In [125]: list(map(sum, zip(*big_list)))
Out[125]: [6, 12, 18, 24, 30]
You have other alternatives to map. For example, using a list comprehension:
In [126]: [sum(x) for x in zip(*big_list)]
Out[126]: [6, 12, 18, 24, 30]

You can store lists in lists and sum over them.
You could have something like this:
list_a = [1,2,3,4,5]
list_b = [2,4,6,8,10]
list_c = [3,6,9,12,15]
list_of_lists = [list_a, list_b, list_c] # this could be 20+ lists
def sum_lists():
temp_list = []
for index in range(len(list_a)):
temp_list.append(sum([l[index] for l in list_of_lists]))
return temp_list
total = sum_lists()

Here's my alternative:
list_a = [1, 2, 3, 4, 5]
list_b = [2, 4, 6, 8, 10]
list_c = [3, 6, 9, 12, 15]
def sum_lists(*arg):
return [sum(i) for i in zip(*arg)]
results = sum_lists(list_a, list_b, list_c)

Related

Python produce alternative numbers list from a list of n numbers

I have a list of n numbers. I want to group them in g groups. Also, I want to reverse elements in every odd group. Finally, I would combine all elements in even and odd groups into a new sublist. First I am giving what answer I am expecting and where I went wrong:
Expected answer:
num = 14
grp = 4
# A list of num natural numbers arranged in group (row) of 4 numbers
lst =
[0,1,2,3,
4,5,6,7,
8,9,10,11,
12,13]
lst =
[[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13]]
# Reverse elements in odd rows
newlst =
[[0,1,2,3],
[7,6,5,4], # reversed here
[8,9,10,11],
[13,12]] # reversed here
# combine elements in all sublists by their position
# combine first element in all sublists into a new sublist
sollst =
[[0,7,8,13],[1,6,9,12],[2,5,10],[3,4,11]]
My solution:
num = 14
grp = 4
#### print
lst= list(range(0,num,1))
newlst= [lst[i:i+grp:1] for i in range(0,num,grp)]
evnlst = newlst[0::2]
oddlst = newlst[1::2]
newoddlst = [oddlst [i][::-1] for i in range(len(oddlst))]
sollst= evnlst + newoddlst
# This gives [[0, 1, 2, 3], [8, 9, 10, 11], [7, 6, 5, 4], [13, 12]]
from itertools import zip_longest
print([[x for x in t if x is not None] for t in zip_longest(fevngps)])
Present answer:
I reached the one step before the final answer and now I have to combine the lists of different lengths and I am running into an error
TypeError: 'int' object is not subscriptable
One approach:
from itertools import zip_longest
num = 14
grp = 4
lst = list(range(0, num, 1))
newlst = [lst[i:i + grp:1] for i in range(0, num, grp)]
# build new list where the sub-list are reversed if in odd indices
revlst = [lst[::-1] if i % 2 == 1 else lst for i, lst in enumerate(newlst)]
# zip using zip_longest and filter out the None values (the default fill value of zip_longest)
result = [[v for v in vs if v is not None] for vs in zip_longest(*revlst)]
print(result)
Output
[[0, 7, 8, 13], [1, 6, 9, 12], [2, 5, 10], [3, 4, 11]]

How can we take out the product of elements?

I have the list named as input_list = [1, 2, 3, 4, 5] , I want to take the product of every elements except the specific index which is running at the moment.
Example
input_list1 = [1, 2, 3, 4, 5]
If I say that in the first index the value is 1 , in the output list, its product will be the all elements except first index (5*4*3*2) and insert it into new list, same goes for all elements.
Expected_Output:
prod = [120, 60, 40, 30, 24]
You can use math.prod for the task:
import math
out = [
math.prod(input_list1[:i] + input_list1[i + 1 :])
for i in range(len(input_list1))
]
print(out)
Prints:
[120, 60, 40, 30, 24]
Let's find the product of all the numbers in the list first.
from functools import reduce
from operator import mul
l = [1, 2, 3, 4, 5]
product = reduce(mul, l, 1)
Once we have it, let's iterate over all items in the list and divide the product by that item. This will give us the product of all the items except that one.
ans = [product // num for num in l]
Time Complexity: O(n)
This should work:
Code:
import math
input_list1 = [1, 2, 3, 4, 5]
def main(l):
final = []
for i in l:
b = lambda a: int(a) if a == int(a) else a
final.append(b(math.prod(input_list1) / int(i)))
return final
prod = main(input_list1)
print(prod)
Output:
[120, 60, 40, 30, 24]
This should work.

Python / Add previous element from a list

I'm quite new to Python and trying to do something but cannot figure out how...
x = 20
list = [5, 3, 7]
I want to create a loop that add the previous element from the list to x
Loop 1 : result = 20+0 = 20 (no previous element)
Loop 2 : result = 20+5 = 25
Loop 3 : result = 20+5+3 = 28
So at the end result should look like that :
result = [20, 25, 28]
Any idea how I could achieve this result ?
Thank you for your help!
Here's how I'd do it:
>>> x = 10
>>> my_list = [5, 3, 7]
>>> [x + sum(my_list[:n]) for n in range(len(my_list))]
[10, 15, 18]
Note that naming a list list is a bad idea because it overwrites the builtin list function!
Try it:
x = 20
my_list = [5, 3, 7]
result = [x]
for i in range(len(my_list)-1):
x += my_list[i]
result.append(x)
print(result)
You can use a list comprehension:
x = 20
lst = [5, 3, 7]
lst = [x+sum([lst[i] for i in range(i)]) if i else x for i,n in enumerate(lst)]
print(lst)
Output:
[20, 25, 28]

How do you compare and return duplicates in two different 2d list?

I would like to return the duplicates in two different 2d lists. But I'm having trouble figuring out what code to write. For example I would like variable "a" to compare to variable "b" and return the duplicates. Here are my two 2d list below.
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
I would like my results to be:
c = [[2,3,6,8],[15,17,21,22]]
You just need to check if a list in a is also in b or not.
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
c=[]
for i in a:
if i in b:
c.append(i)
print(c)
Output:
[[2, 3, 6, 8], [15, 17, 21, 22]]
This should work, it should get you started -
import itertools
#Input lists
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
#Take a product of both the lists ( a X b )
z = itertools.product(a,b)
#Uncomment the following to see what itertools.product does
#[i for i in z]
#Return only the elements which the pair of the same element repeats (using string match)
[i[0] for i in z if str(i[0])==str(i[1])]
[[2, 3, 6, 8], [15, 17, 21, 22]]
one liner list comprehension approach:
dups = [i for i in a if i in b]
output:
[[2, 3, 6, 8], [15, 17, 21, 22]]
Try this:
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
c = []
for i in a + b:
if (a + b).count(i) > 1 and i not in c:
c.append(i)
#mulaixi's answer is OK but in output list you may see duplicates.

how to returns the index of the smallest element in the list in python

In my code, returns the position of the smallest element in the list by use index() function, when I run the code, it run nothing. Please help me to figure out problem. Here is what I coded:
def get_index_of_smallest(numbers):
smallest_index = []
for element in range (len(numbers)):
element = numbers.index(min(numbers))
smallest_index = element + 1
return smallest_index
def test_get_index_of_smallest():
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print(get_index_of_smallest(list1))
Many thanks.
You can use min(list) and builtin function of list(list.index())
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
min_num = min(list1)
index = list1.index(min_num)
One way, it's possible using min, emumerate and lambda
myList = [23, 3, 6, 5, 12, 9, 7, 4]
min(enumerate(myList), key=lambda x:x[1])[0]
#1
Your code looks good, but you forgot to call the function. Add test_get_index_of_smallest(), and it will work!
Input:
def get_index_of_smallest(numbers):
smallest_index = []
for element in range (len(numbers)):
element = numbers.index(min(numbers))
smallest_index = element + 1
return smallest_index
def test_get_index_of_smallest():
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print(get_index_of_smallest(list1))
test_get_index_of_smallest()
Output:
2
Edit:
You can further cut down your code. Here is a code that does the same thing:
Input:
def get_index_of_smallest(numbers):
return numbers.index(min(numbers))+1
print(get_index_of_smallest([23, 3, 6, 5, 12, 9, 7, 4]))
Output:
2
We can use list comprehension and enumerate here
min_idx = [idx for idx, item in enumerate(list1) if item == min(list1)]
[1]
Here is a expanded version of what is going on here
for idx, item in enumerate(list1):
if item == min(list1):
min_idx = idx
When we enumerate in it iterates for the index and item so what we can do is check each item v min(list1) if we get a match we can set our min_idx variable to the corresponding index of that item, cheers !

Categories