I'm trying to solve how to multiply all even numbers in a list with 2, and add all odd numbers with 7. And then present the list in an descending order. It has to be with a function that takes the list as argument.
I found this here on stackoverflow, but it's not really what I'm after, since the example sums up the even numbers to one product.
This is my code:
L = [45, 22, 2, 498, 78]
def EvenOdd(L):
product = 2
resp = 7
elem = None
for elem, val in enumerate(L):
elem += 1
if elem % 2 == 0:
product *= elem
if elem % 2 == 1:
resp += elem
result = L[elem]
result.sort()
result.reverse()
print(result)
You can create new list using:
new_list = [item * 2 if item % 2 == 0 else item + 7 for item in L]
and then sort it using:
new_list.sort(reverse=True)
Output should look like this:
[996, 156, 52, 44, 4]
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.