简体   繁体   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)

I need assistance with creating a list or an array from the results of the For loop.我需要帮助根据 For 循环的结果创建列表或数组。

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.注意: range默认步长为1 ,因此可以在此处跳过。 List comprehensions are generally faster than appending elements to list in for loop.列表理解通常比将元素附加到for循环中的列表更快。 It's also more pythonic way of doing such tasks.它也是执行此类任务的更多 pythonic 方式。

# 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 For循环

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使用适合您需要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何自动创建对象(例如在循环中) - How to create an object automatically (e.g. in a loop) 如何在列表的值之间运行循环,例如 List = [0, 417, 2050, 2221, 3039] - How to run loop in between the values of list for e.g. List = [0, 417, 2050, 2221, 3039] 如何在 Python 中创建 x 列表(例如使用 while 循环)? - How do I create x lists in Python (e.g. with a while-loop)? 如何以交互方式(例如使用终端)干预 for 循环 - How to interactively (e.g. using the terminal) intervene a for loop 从python列表中删除项目,如何比较项目(例如numpy数组)? - Removal of an item from a python list, how are items compared (e.g. numpy arrays)? Python:如何创建一个函数? 例如 f(x) = ax^2 - Python: How to create a function? e.g. f(x) = ax^2 全屏终端output(例如在网格上) - Fullscreen terminal output (e.g. on a grid) 如何将字符串(例如'A')引用到更大列表的索引(例如['A','B','C','D',...])? - How can I reference a string (e.g. 'A') to the index of a larger list (e.g. ['A', 'B', 'C', 'D', ...])? 如何从环境中接收数据,例如bash - How to receive data from the environment e.g. bash 切片`a`(例如`a [1:] == a [: - 1]`)是否创建了`a`的副本? - Does Slicing `a` (e.g. `a[1:] == a[:-1]`) create copies of the `a`?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM