python - 在 Python 中 append 到列表的美学方式?

标签 python list syntax append

当将较长的语句 append 到列表时,我觉得 append 变得难以阅读。我想要一种适用于动态列表创建的方法(即不需要先用零初始化等),但我似乎无法想出另一种方法来做我想做的事。

示例:

import math
mylist = list()
phi = [1,2,3,4] # lets pretend this is of unknown/varying lengths
i, num, radius = 0, 4, 6

while i < num:
    mylist.append(2*math.pi*radius*math.cos(phi[i]))
    i = i + 1

虽然 append 工作得很好,但我觉得它不如以下清晰:

mylist[i] = 2*math.pi*radius*math.cos(phi[i])

但这不起作用,因为列表中还不存在该元素,产生:

IndexError: list assignment index out of range


可以只将结果值分配给临时变量,然后追加它,但这看起来很丑陋且效率低下。

最佳答案

您不需要现有列表并稍后 append 到它。只需使用列表理解

列表理解,

  • 速度很快,
  • 易于理解,
  • 并且可以轻松移植为生成器表达式

    >>> import math
    >>> phi = [1,2,3,4]
    >>> i, num, radius = 0, 4, 6
    >>> circum = 2*math.pi*radius
    >>> mylist = [circum * math.cos(p) for p in phi]
    

检查您的代码,这里有一些通用的建议

  • 不要在迭代中计算已知常量

    while i < num:
        mylist.append(2*math.pi*radius*math.cos(phi[i]))
        i = i + 1
    

应该写成

circum = 2*math.pi
while i < num:
    mylist.append(circum*math.cos(phi[i]))
    i = i + 1
  • 代替 while 使用 for-each 结构

    for p in phi:
        mylist.append(circum*math.cos(p))
    
  • 如果一个表达式不可读,将其分成多个语句,毕竟在 Python 中可读性很重要。

关于python - 在 Python 中 append 到列表的美学方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13818992/

相关文章:

python - 尝试在 python 中定义一系列数字变量时出现语法错误

python - 编译/执行未能在它自己的范围内分配值,导致内部语法错误

c# - 向 MySQL 中插入多列时出现语法错误

python - Malloc 与 nogil 一起使用安全吗?

python - 将以 [1,0,-1] 开始和结束的列表转换为阶跃函数 [0, 1]

python - 如何获取python中列表列表的统计信息?

list - Haskell 中的字数统计

python - 在大数据集的 pandas 数据框中搜索和替换

python - Keras 与 TensorFlow : Use memory as it's needed [ResourceExhaustedError]

python - 发送 SIGINT 后从子进程捕获标准输出