简体   繁体   中英

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:

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. Then use functools.reduce to multiply the elements together.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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