I would like to only combine elements of lists that dont give 0 when multiplied with each other.
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = [0, 0, 3, 0, 5]
Since 1x10x0 = 0, 2x20x0 = 0, 3x30x3 = 270, 4x40x0 = 0, 5x50x5 = 1250
only combine
a = [3, 5]
b = [30, 50]
c = [3, 5]
expected output:
d = [(3,30,3), (5,50,5)]
CodePudding user response:
list = []
for i in range(len(a)):
if 0 in [a[i], b[i], c[i]]:
continue
else:
list.append((a[i], b[i], c[i]))
print(list)
CodePudding user response:
You can do something like
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = [0, 0, 3, 0, 5]
final_ouput=[(x,y,z) for x,y,z in zip(a,b,c) if x * y* z !=0]
Output
[(3, 30, 3), (5, 50, 5)]
CodePudding user response:
Use zip
to iterate the lists in parallel.
As you deal with integers, you could use all
to identify if you have any zero (in which case the product will be 0):
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = [0, 0, 3, 0, 5]
d = [x for x in zip(a,b,c) if all(x)]
output: [(3, 30, 3), (5, 50, 5)]
How it works:
all
will check if all values in an iterable are truthy. For integers, 0 is the only non truthy value. So all(list_of_integers)
is False
if any value is 0, and True
otherwise.
Alternative syntax:
An alternative syntax could be to use filter
:
d = list(filter(all, zip(a, b, c)))