Skip to main content
 首页 » 编程设计

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

2025年05月04日24Free-Thinker

当将较长的语句 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 中可读性很重要。