简体   繁体   English

如果 function 用于列表中的每个元素,如何应用?

[英]How to apply if function for every element in a list?

I have a list1 = [3,4,5,6,7,8] .我有一个list1 = [3,4,5,6,7,8] I want append to a list2 such that Add 10 to even number and multiply with 5 if it is an odd number in the list1 with Python.我希望 append 到list2中,以便Add 10even numbermultiply with 5 ,如果它是list1中的奇数,则使用 Python。

I've tried this我试过这个

list1 = [3, 4, 5, 6, 7, 8]

list2 = []

for num in list1:
    if (num%2) == 0:
        num + 10
        list2.append(num)
    else:
        num*5
        list2.append(num)

list2

got it...知道了...

import numpy as np

list1 = [3, 4, 5, 6, 7, 8]

list2 = []

for num in list1:
    if (num%2) == 0:
        x = num + 10
        list2.append(x)
    else:
        x = num*5
        list2.append(x)

list2

You are not storing num+10 or num*5 anywhere.您没有在任何地方存储num+10num*5 Try this -尝试这个 -

list1 = [3, 4, 5, 6, 7, 8]

list2 = []

for num in list1:
    if (num%2) == 0:
        list2.append(num + 10) #<----
    else:
        list2.append(num*5)    #<----
        
list2
[15, 14, 25, 16, 35, 18]

You can also try using list comprehension which is a one liner that does the same thing as above -您也可以尝试使用列表理解,它是一种与上述功能相同的内衬 -

list2 = [num+10 if (num%2)==0 else num*5 for num in list1]
[15, 14, 25, 16, 35, 18]

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

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