python3 数组(列表)初始化
1. 初始化一个定长的数组
有时需要预定义一个定长的数组,并给每个元素赋值
方法1: python3中代码如下:
#coding=utf-8
item = ‘PythonTab’
array = [item for v in range(10)] #把 item 的值赋给 range()迭代器的每个元素
print(array)
结果:
[‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’]
方法2: python3中代码如下:
item = ‘PythonTab’
array = [item]*10
print(array)
结果:
[‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’, ‘PythonTab’]
2. 初始化创建n行m列数组
#coding=utf-8
n = 3
m = 3
matrix = [‘init’]*n
for i in range(len(matrix)):
matrix[i] = [‘PY’]*m #把init的值覆盖了
print(matrix)
结果:
[[‘PY’, ‘PY’, ‘PY’], [‘PY’, ‘PY’, ‘PY’], [‘PY’, ‘PY’, ‘PY’]]