Python 3.x:列表的条件乘法元素

dtcbnfnu  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(142)

如何将列表中的某些数字相乘?例如:

if i >= 3:
    result = [i* 3 for i in list]
if i < 3:
    result = [i * 2 for i in list]
``

我已经尝试了以下功能,但没有成功:

def special_multiply(list, multiplicator,multiplicator_2):
    for i in list:
        if i >= 3:
            result = [i* multiplicator for i in list]
        if i < 3:
            result = [i * multiplicator_2 for i in list]
        return result

print("Special multiply:", special_multiply([1,2,3,4,5,6],2,3))
I expected following output:[2,4,9,12,15,18]

提前感谢!

inn6fuwd

inn6fuwd1#

请尝试以下操作:

def special_multiply(parameterList, multi, multi2):
    returnList = []
    for i in parameterList:
        if i >=3:
            returnList.append(i*multi2)
        else:
            returnList.append(i*multi)
return returnList

相关问题