将列表中的值附加到python中的空列表

时间:2017-12-08 15:22:19

标签: python list for-loop iteration

一个列表包含值,一个列表为空。我想从列表中取出两个带有数据的值,并使用for循环将其放入空列表中。我知道如何获得一个价值。但是,我不知道如何获得另一个。以下是我的代码:

 all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']
# The above list is a list of all fruits

# Now lets creat a blank list called favorite fruit
favorite_fruit = []

# The objective is to choose two fruits from the all fruits list and append them to the favorite fruit list

for fruit in all_fruits:
    if fruit == 'apples':
        favorite_fruit.append(fruit)



print favorite_fruit

Output: ['apples']

我希望favorite_fruit变量输出['apples', 'peaches']['apples', 'cherry']。我该怎么做呢?谢谢

2 个答案:

答案 0 :(得分:0)

您只需在for循环中添加一个条件即可检测第二个最喜欢的水果。

for fruit in all_fruits:

    if fruit == 'apples' or fruit == 'peach':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples', 'peach']

或者一般来说,您可以将喜爱的水果列表构建为初始类似的过滤列表。

def is_a_favorite_fruit(fruit):
    return fruit == 'apples' or fruit == 'peach'

favorite_fruits = [fruit for fruit in all_fruits if is_a_favorite_fruit(fruit)]

print favorite_fruit

Output: ['apples', 'peach']

答案 1 :(得分:0)

你可以在没有循环的情况下一行完成:

all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']

print(list(filter(lambda x:x=='apples' or x=='peach',all_fruits)))

输出:

['apples', 'peach']