简体   繁体   中英

Reversing a List Comprehension

sorry for the beginners question but I've spent too long messing about with this so far andI'm sure it's a simple solution.

So

For the exercise I am changing this simple list comprehension back to a for loop :

numbers = [n for n in range(10)]
listcomp = [n/2 for n in numbers if n%2 == 0]

Obviously all this does is take numbers 0 to 9, divides them by 2 to give floats from 0.0 to 4.5, and then removes entries from the list whose remainders when divided by 2 are not equal to 0, leaving only the whole numbers from 0.0 to 4.0. Here is what I thought would work, the problem at the moment is that the if statement and the second append appear to have no effect and I'm not sure why. I would like to understand this problem if anyone can explain.

numbers = []
newlist = []
for num in range(0, 10):
    numbers.append(num/2)
for n in numbers:
    if n%2 == 0:
        newlist.append

For the first loop, you're iterating through the range and appending the value of each number in that range divided by two. In the first list comprehension, all you do is create a list that contains all of the integers in that given range. In the second for loop, you're basically checking if the number is even, and then not appending the number at all: newlist.append . In the second list comprehension, you append the number divided by two if the number is even.

Change your loops to:

for num in range(0, 10):
    numbers.append(num)
for n in numbers:
    if n%2 == 0:
        newlist.append(n/2)

It may also be worth noting that instead of iterating through a range of numbers and then just appending that number, you can make your code cleaner by replacing the first for loop with:

mylist = list(range(10))

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