Reputation: 13
I want to write an if-statement for this list:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
lst= ([[a, b, c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1)])`
I want to add a, b and c in all lists and if they are not equal to n, print each of them. How should I do that?
Upvotes: 1
Views: 48
Reputation: 4449
A filter
& itertools
approach:
> a, b, c, n = 1, 1, 1, 2
> all_combos = itertools.product(range(a+1), range(b+1), range(c+1))
> lst = list(filter(lambda x: sum(x) != n, all_combos))
> print(lst)
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (1, 1, 1)]
Upvotes: 0
Reputation: 6904
you can use an if condition
in list comprehension , which makes this easy to achieve
lst= ([[a, b, c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a+b+c != n])
Upvotes: 1
Reputation: 9
lst = []
for a in range(0, x + 1):
if a != n:
print(a)
lst.append(a)
for b in range(0, y + 1):
if b != n:
print(b)
lst.append(b)
for c in range(0, z + 1):
if c != n:
print(c)
lst.append(c)
You can use if statement inside list comprehension but not in this context because you will need an else statement
Upvotes: 0