私はちょうどパスカルの三角形から始めて、いくつかのpython演習で練習を始めました。 各行を格納するリストのリストを選択しました。以下は Pythonでリストのリストを操作する
は私のコードです:import sys
list = []
listoflists = [[1],[1,1]]
def pascalgeneration(func_list, cur_row, total_row):
print("FUNCTION ENTERED\n CUR ROW \n TOTAL ROW",cur_row,total_row)
while (cur_row < total_row):
for iter in range(0, cur_row+1):
if (iter == 0):
func_list[cur_row].append(1)
elif(iter == cur_row):
func_list[cur_row].append(1)
func_list.append(list)
break
else:
print ("INSIDE ELSE BLOCK\n CUR_ROW \n TOTAL_ROW\n ITER VARIABLE",cur_row,total_row,iter)
func_list[cur_row].append(func_list[cur_row-1][iter-1]+\
func_list[cur_row-1][iter])
cur_row += 1
print (func_list)
def main():
no_rows = int(input("Enter the number of rows :"))
#print (type(no_rows))
if (no_rows==1):
print (listoflists[0][0])
elif(no_rows==2):
print (listoflists[1][0],listoflists[1][1])
else:
listoflists.append(list)
pascalgeneration(listoflists,2,no_rows)
#print (listoflists)
if __name__ == "__main__":
main()
しかし、私はこのコードを実行すると、出力に含まはexepectedようではありません。
を入力とする5:
OUTPUTは
のようなものです[[1],
[1,1],
[1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 2, 1],
[1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 2, 1],
[1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 2, 1],
[1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 2, 1]
]
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
誰かが私にリストのリストの動作を説明できますか?
また、変数名の使用に関する貴重な提案に感謝します:) – user3275349