简体   繁体   English

列表列表:添加每个列表中的所有项目

[英]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: filteritertools方法:

> 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.

相关问题 如何在Python的列表列表中添加所有项目 - How to add all items in a list of lists in Python 在列表列表中,如何获取除每个列表的最后一个项目以外的所有项目? - In a list of lists how to get all the items except the last one for each list? 列表列表或多个列表可以元素组合的所有方式是什么 - 对每个列表中具有相同索引的项目进行操作? - What are all the ways that a list of lists or multiple lists can be combined elementwise - operate on the items from each list with the same index? Python列表列表中的所有项目为true - Python all items in list of lists true 尝试在元组列表列表中添加项目 - Trying to add items in list of lists of tuples 将项目的每个子列表添加到Python中的列表列表 - Add an Item each sublist to the list of Lists in Python 如何将多个列表转换为子列表列表,其中每个子列表由所有列表中的相同索引项组成? - How to turn multiple lists into a list of sublists where each sublist is made up of the same index items across all lists? 如何从单独列表中的列表列表中清空所有项目 - How to empty all items from a list of lists in a separate list 相互减去列表中的所有项目 - Subtract all items in a list against each other list1的每个元素的列表总和,而list2中的所有元素 - Sum of lists for each element of list1 with all in list2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM