[英]Python: list comprehension based on previous value?
假設我想使用列表理解創建一個列表,例如:
l = [100., 50., 25., 12.5, ..., a_n]
...即,從某個數字開始,然后從同一列表中的那個數字生成 n 個“一半”。 我可能會遺漏一些簡單的 Pythonic 方法,或者我只需要依靠一個好的 ol' for 循環。 這能做到嗎? 謝謝。
這個怎么樣?
start = 2500.0
n = 50
halves = [start / 2.0**i for i in range(n)]
等於:
[start * 2.0**(-i) for i in range(n)]
與@DeepSpace 的答案相比,效率可能較低,但只有一行
定義一個生成器,並在列表推導式中使用它:
def halve(n):
while n >= 1:
yield n
n /= 2
print([_ for _ in halve(100)])
>> [100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625]
或者簡單地將其轉換為列表:
print(list(halve(100)))
>> [100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625]
編輯如果@R Nar 的評論是正確的:
def halve(start, n):
for _ in range(n):
yield start
start /= 2
print(list(halve(100, 3)))
>> [100, 50.0, 25.0]
print(list(halve(100, 4)))
>> [100, 50.0, 25.0, 12.5]
試試這個(Python 3.8.5):
from itertools import accumulate
n=5
result = list(accumulate(range(n), lambda acc, val: acc/2, initial=100))
print(result)
以下代碼適用於 int 但不適用於浮點數。
[100>>i for i in range(10)]
這將返回:
[100, 50, 25, 12, 6, 3, 1, 0, 0, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.