簡體   English   中英

如何從 for 循環 output 創建結構(例如列表)?

[英]How to Create a structure (e.g. a list) from a for loop output?

u = range(1,30,1)
for s in u:
    print(s**-1*500)

我需要幫助根據 For 循環的結果創建列表或數組。

使用列表理解。

u = [s**-1*500 for s in range(1,30)]

注意: range默認步長為1 ,因此可以在此處跳過。 列表理解通常比將元素附加到for循環中的列表更快。 它也是執行此類任務的更多 pythonic 方式。

# Create an empty list
item_list = []
for s in u:
    # Append each item to list.
    item_list.append(s**-1*500)

你有兩種方法可以做到。

For循環

u = range(1,30,1)
values = []
for s in u:
    values.append(s**-1*500)

列表理解

values = [s**-1*500 for s in range(1,30,1)]

使用適合您需要的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM