2024-04-20 10:55:21 发布
网友
如果您在此处有此列表:
[25, 8, 22, 9]
如何让程序创建两个单独的列表,并打印它们?一个应该包含所有小于20的数字,另一个需要包含所有大于20的数字。最终的打印结果应该这样显示:[8, 9],[25, 22]
[8, 9]
[25, 22]
def print_split_list(raw_list, split_value): lower_list = [v for v in raw_list if v < split_value] upper_list = [v for v in raw_list if v >= split_value] print lower_list, upper_list print_split_list([25, 8, 22, 9], 20) # => [8, 9] [25, 22]
>>> predicates = lambda x:x<20, lambda x:x>20 >>> print [filter(pred, [25, 8, 22, 9]) for pred in predicates] [[8, 9], [25, 22]]
使用list comprehensions:
>>> L = [25, 8, 22, 9] >>> [x for x in L if x < 20] [8, 9] >>> [x for x in L if x > 20] [25, 22]
使用list comprehensions:
相关问题 更多 >
编程相关推荐