简体   繁体   English

修改/创建新列表

[英]Modification/creation of new lists

I have been tasked with finding the even numbers from this list and multiplying them all together.我的任务是从这个列表中找到偶数并将它们相乘。 I have used modulus to find the evens, and have a way of multiplying a list, however I do not know how to place the even values found by the modulus into a new list to be modified.我已经使用模数来找到偶数,并且有一种将列表相乘的方法,但是我不知道如何将模数找到的偶数值放入要修改的新列表中。

Here is the list:这是列表:

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21] 

and here is what I have for finding even:这是我什至要找到的东西:

for num in list3:
    if (num % 2 ==0):
print(even_list)

and I am using a multiplication function I created earlier:我正在使用我之前创建的乘法 function:

def multiply_list(list1):
    result = 1
    for num in list1:
        result = result * num
    return result

Forgive me, I am sure this is an easy fix.原谅我,我相信这很容易解决。 I am very new to this.我对此很陌生。

I am not sure if I understood your question properly.我不确定我是否正确理解了你的问题。 Below is the code to insert elements in the list.下面是在列表中插入元素的代码。

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21]

even_list = []

for num in list3:
    if (num % 2 ==0):
        even_list.append(num)

print(even_list)

If you want to multiply the even elements in the list, use below code.如果要将列表中的偶数元素相乘,请使用以下代码。

def evenList(list):
    even_list = []
    for num in list:
        if (num % 2 ==0):
            even_list.append(num)
            
    return even_list
            
def multiply_list(list1):
    result = 1

    for num in list1:
        result = result * num

    return result

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21]

print(multiply_list(evenList(list3)))

The list of even numbers can be found by using a for loop, or a list comprehension for more concise syntax.偶数列表可以通过使用 for 循环或更简洁语法的列表理解来找到。 Then use functools.reduce to multiply the elements together.然后使用functools.reduce将元素相乘。

from functools import reduce

list3 = [146, 875, 911, 83, 81, 439, 44, 5, 46, 76, 61, 68, 1, 14, 38, 26, 21] 

even_list = [n for n in list3 if n % 2 == 0]
print(even_list)  # [146, 44, 46, 76, 68, 14, 38, 26]

even_product = reduce(lambda product, n: n*product, even_list)
print(even_product)  # 21123741743104

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

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