简体   繁体   English

反转列表理解

[英]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 :在练习中,我将这个简单的列表理解改回 for 循环:

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.显然所有这一切都是取数字 0 到 9,将它们除以 2 得到从 0.0 到 4.5 的浮点数,然后从列表中删除除以 2 的余数不等于 0 的条目,只留下从 0.0 到 4.5 的整数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.这是我认为可行的方法,目前的问题是 if 语句和第二个 append 似乎没有效果,我不知道为什么。 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.对于第一个循环,您将遍历范围并附加该范围内每个数字除以 2 的值。 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 .在第二个 for 循环中,您基本上是在检查数字是否为偶数,然后根本不附加数字: 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:还可能值得注意的是,您可以通过将第一个 for 循环替换为:

mylist = list(range(10))

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

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