如何为Python列表推导式添加条件,筛选a+b+c≠n的子列表并打印
解决方案
你可以通过两种简洁的方式实现需求:
方法1:列表推导式内直接过滤
直接在生成列表的推导式中加入判断条件,只保留a+b+c != n的子列表,再逐个打印:
x = int(input()) y = int(input()) z = int(input()) n = int(input()) # 生成时过滤掉和为n的子列表 filtered_lst = [[a, b, c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n] # 遍历打印每个符合条件的子列表 for item in filtered_lst: print(item)
方法2:遍历原列表后判断过滤
如果需要保留完整的全量列表,也可以先生成所有可能的子列表,再遍历判断并打印符合条件的项:
x = int(input()) y = int(input()) z = int(input()) n = int(input()) full_lst = [[a, b, c] for a in range(x+1) for b in range(y+1) for c in range(z+1)] # 逐个检查并打印和不等于n的子列表 for sub_list in full_lst: if sum(sub_list) != n: print(sub_list)
补充说明
- 方法1的效率更高,因为它在列表生成阶段就过滤掉了不符合要求的元素,无需存储全量数据
- 方法2适合需要后续复用全量列表的场景
内容的提问来源于stack exchange,提问作者Maze
相关产品推荐
相关产品推荐

