我正在为20个键建立一个相关矩阵,需要创建一个如下所示的数组,并且想知道如何使用循环来创建这样的数组。
[[1],
[0.3, 1],
[0.3, 0.3, 1],
[0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 1],
[0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 1]]
答案 0 :(得分:4)
您可以通过以下方式获取它:
[[0.3 for x in range(y)] + [1] for y in range(20)]
或等效地,通过:
[[0.3] * y + [1] for y in range(20)]
答案 1 :(得分:2)
此处是代码的扩展版本。
#!/usr/bin/env python3
def generate_stepped_list(steps, last_number, repeated_number):
"""
" @return a list (of `steps` length) of lists where each inner list is
" one time longer than the previous one.
" Lines are padded with repeated_number until the last position with
" contains the last_number.
" [[last_number], -
" [repeated_number, last_number], ^
" [repeated_number, repeated_number, last_number] | steps
" ... |
" [repeated_number, ... , repeated_number, last_number]] -
"""
stepped_list = []
for i in range(steps):
step = [repeated_number for x in range(i)]
step.append(last_number)
stepped_list.append(step)
return stepped_list
if __name__ == "__main__":
stepped_list_12 = generate_stepped_list(12, 1, 0.3)
print(stepped_list_12)
这里使用列表推导(与@dcg相同,是对的)压缩了代码。
#!/usr/bin/env python3
def generate_stepped_list(steps, last_number, repeated_number):
return [[repeated_number] * y + [last_number,] for y in range(steps)]
if __name__ == "__main__":
stepped_list_12 = generate_stepped_list(12, 1, 0.3)
print(stepped_list_12)
答案 2 :(得分:-1)
所需的模式可以在嵌套循环的帮助下完成:-
pattern = [] # Creating list to store pattern by append method in list.
for x in range(12):
start = [1]
for y in range(x):
start = start + [0.3]
pattern.append(start)
print(pattern)
for var in pattern:
print(var)