简体   繁体   English

如何从一个列表中返回2个单独的列表?

[英]How to return 2 separate lists from a single list?

If have this list here: 如果在这里有此列表:

[25, 8, 22, 9] 

How can I make the program create 2 seperate lists, and print them both? 如何使程序创建2个单独的列表,并同时打印它们? One should contain all the numbers less than 20, and the other needs to contain all the numbers greater than 20. The final print result should be displayed like this: [8, 9] , [25, 22] 一个应包含所有小于20的数字,另一个应包含所有大于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]]

Use 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]
a =  [25, 8, 22, 9] 
print [x for x in a if x > 20]
print [x for x in a if x < 20]

You use here list comprehensions . 您在此处使用列表推导 List comprehension looks like: 列表理解如下:

[ f(x) for x in a if cond(x) ]

That means: produce me a list that consists of f(x) for each element of x for that cond(x) is True . 这意味着:产生我由一个列表f(x)的每个元素xcond(x)True

In our case f(x) is simply x . 在我们的情况下, f(x)只是x And cond(x) is x > 20 or x < 20 (please note also that if you have 20s in your list, they will disappear from the result). cond(x)x > 20x < 20 (请注意,如果列表中有20s,它们将从结果中消失)。

If it is a homework you can solve the task in more low-level way: 如果这是一项家庭作业,则可以以更底层的方式解决任务:

a = [25, 8, 22, 9]
list1 = []
list2 = []
for elem in a:
  if elem > 20:
     list1.append(elem)
  if elem < 20:
     list2.append(elem)
print list1
print list2

Here you iterate through the list and check its elements. 在这里,您可以遍历列表并检查其元素。 That elements that are greater than 20 you append to one list; 您将大于20的元素追加到一个列表中; and that that are lesser thatn 20 — to the other. 那比那少20。

Note: the assumes you want twenty in listTwo 注意:假设您要在列表中二十

listOne = [x for x in yourList if x < 20]
listTwo = [x for x in yourList if x >= 20]

print listOne
print listTwo

Although you should use list comprehensions you might be interested in the for loop approach if you are starting with python 尽管您应该使用列表推导 ,但如果您是从python开始的,则可能会对for循环方法感兴趣

listOne = []
listOne = []

for x in yourList:
    if x < 20:
        listOne.append(x)
    else:
        listTwo.append(x)
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]
li = [25, 8, 22, 9]
li.sort()

for i, x in enumerate(li):
    if x > 20:
        print li[:i]
        print li[i:]
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM