2017-12-08 8 views
-2

リストには値が1つあり、1つは空です。私はデータからリストから2つの値を取り出し、forループを使用して空のリストに入れたいと思います。私は一つの価値を得る方法を知っています。しかし、私はどのように他を取得するか分からない。私は、出力['apples', 'peaches']または['apples', 'cherry']からfavorite_fruit変数をしたいリストから空のリストに値を追加する

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'] 

:ここでは以下の私のコードです。これをどうやって行うのですか?ありがとう

+2

りんごのインデックスを取得し、そのインデックス – smac89

+0

別を追加あなたの好きな果物は何だと判断していますか?ランダムですか?最初の2? – bigbounty

+0

から反復 – depperm

答えて

0

2番目のお気に入りの果物を検出するために、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'] 
+0

私はそれを理解していますが、favorite_fruitリストが印刷されると、それは「りんご」だけを印刷します。私はそれが追加されているもののすべてのリストを印刷したい。 @Olivier –

+0

それはそうするでしょう、あなたが他に何も追加しなかっただけです。 –

0

あなたはループせずに1行で行うことができます。

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

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

出力:if文

['apples', 'peach'] 
関連する問題