[英]How should I append all my results to one list after each iteration in the python?
def pascalstriangle(n):
list = [1]
for i in range(n):
print(list)
newlist = []
newlist.append(list[0])
for i in range(len(list) - 1):
newlist.append(list[i] + list[i + 1])
newlist.append(list[-1])
list = newlist
print(pascalstriangle(3))
我想查看這種打印格式[1,1,1,1,2,1]
而不是
[1]
[1, 1]
[1, 2, 1]
要修復以上代碼,無論何時打印list
都可以將其添加到其他列表中( 在下面的代碼中,使用extend
將它們添加到final_list
),最后在函數末尾將其返回:
def pascalstriangle(n):
list = [1]
final_list = []
for i in range(n):
final_list.extend(list)
newlist = []
newlist.append(list[0])
for i in range(len(list) - 1):
newlist.append(list[i] + list[i + 1])
newlist.append(list[-1])
list = newlist
return final_list
print(pascalstriangle(3))
結果:
[1, 1, 1, 1, 2, 1]
您可能要考慮的一件事是不使用list
作為變量,而不使用諸如my_list
東西。
您可以像這樣在Python中合並兩個列表:
print([1, 2] + [3])
> [1, 2, 3]
希望對您有所幫助!
只需合並兩個列表:
final_list = list1 + list2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.