Python列表解析 [英] Python List Comprehensions
问题描述
我正在学习python3列表理解.我了解如何格式化列表理解:[等式,for循环,如果要过滤的if语句],但是我无法弄清楚如何将三行代码浓缩为等式"部分的单个等式.
I am learning python3 list comprehensions. 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.
我要获取一个数字并将其添加到自身中,然后获取结果并将其添加到自身中,以此类推,以在列表中创建一个数字序列.
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.
我可以通过声明x = 1然后循环执行以下操作来实现此目的:
I can accomplish this by declaring x = 1 and then looping the following:
y = x + x
y = x + x
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?
推荐答案
您的算法等效于乘以2的幂:
Your algorithm is equivalent to multiplying by powers of 2:
x = 3
res = [x * 2**i for i in range(10)]
# [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]
要了解为什么是这种情况,请注意,在 for
循环的每次迭代中,您都将起始数字乘以2:
To see why this is the case, note you are multiplying your starting number by 2 in each iteration of your for
loop:
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]
正如@timgeb所提到的,您不能随便引用列表理解的元素,因为在理解完成之前这些元素不可用.
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.
这篇关于Python列表解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!