[英]List of lists: add all items in each list
I want to write an if-statement for this list:我想为这个列表写一个 if 语句:
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.我想在所有列表中添加 a、b 和 c,如果它们不等于 n,则打印它们中的每一个。 How should I do that?我该怎么做?
you can use an if condition
in list comprehension, which makes this easy to achieve您可以在列表理解中使用if condition
,这很容易实现
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])
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您可以在列表理解中使用 if 语句,但不能在此上下文中使用,因为您将需要一个 else 语句
A filter
& itertools
approach: filter
和itertools
方法:
> 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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.