简体   繁体   中英

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)

I need assistance with creating a list or an array from the results of the For loop.

Use list comprehension.

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

Notes: range default step is 1 so it could be skipped here. List comprehensions are generally faster than appending elements to list in for loop. It's also more pythonic way of doing such tasks.

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

You have 2 ways to do it.

For loop

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

List Comprehension

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

Use whichever suits your need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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