[英]Python List Comprehensions
I am learning python3 list comprehensions. 我正在学习python3列表理解。 I understand how to format a list comprehension: [equation, for loop, if statement for filtering], but I cannot figure out how to condense three lines of code into a single equation for the 'equation' part. 我理解如何格式化列表理解:[equation,for loop,if if statement for filtering],但我无法弄清楚如何将三行代码压缩成'equation'部分的单个等式。
I am taking a number and adding it to itself and then taking the result and adding it to itself and so on to create a sequence of numbers in the list. 我正在取一个数字并将其添加到自身,然后将结果添加到自身,依此类推,在列表中创建一系列数字。
I can accomplish this by declaring x = 1 and then looping the following: 我可以通过声明x = 1然后循环以下来完成此操作:
y = x + x y = x + x
x = y x = y
Can anybody help me to turn this into a single-lined equation and if possible, resources that I might study to help me with this in the future? 任何人都可以帮我把它变成一个单行方程式,如果可能的话,我可能会研究哪些资源来帮助我解决这个问题?
Your algorithm is equivalent to multiplying by powers of 2: 您的算法相当于乘以2的幂:
x = 3
res = [x * 2**i for i in range(10)]
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
To see why this is the case, note you are multiplying your starting number by 2 in each iteration of your for
loop: 要了解为什么会出现这种情况,请注意您在for
循环的每次迭代中将起始数乘以2:
x = 3
res = [x]
for _ in range(9):
y = x + x
x = y
res.append(y)
print(res)
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
As @timgeb mentions, you can't refer to elements of your list comprehension as you go along, as they are not available until the comprehension is complete. 正如@timgeb所提到的,你不能在你进行时引用列表理解的元素,因为在理解完成之前它们是不可用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.