Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save condorheroblog/8d8811174a9d3365b56d8ec8e5636cfc to your computer and use it in GitHub Desktop.
Save condorheroblog/8d8811174a9d3365b56d8ec8e5636cfc to your computer and use it in GitHub Desktop.

在 Python 中怎样初始化一个 list

方括号

arr = [1, 2, 3]

list 方法

arr = list([0, 1, 2])

方括号和 list 方法初始化比较简短的列表,而下面两种方法比较适合初始化长的列表,例如一百个全为零的数组。

列表乘法

count = [0] * 100
#[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

列表推导式

count = [0 for i in range(0, 100, 1)]
#[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

append

加入不知道列表的长度就尴尬了,所以需要动态添加元素:

arr = []
for i in range(0, 100, 1):
    arr.append(0)
print(arr)

总结

  • 短列表,使用方括号和 list 方法。
  • 长列表,使用列表推导式和乘法。
  • 动态列表,使用 append 方法。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment