以下是我的 Code:
YogaTeacher = ("Kino", "Laruga", "DanySa")
BasketballPlayer = ["MJ", "LBJ", "Shaq"]
temp = [[[], [], []]] * 3
for i,j in enumerate (YogaTeacher):
if (j == "DanySa"):
for k, l in enumerate (BasketballPlayer):
temp[i][k] = l
print (temp)
使用 Python IDE Spyder 印出的 Console 如下所示:
[['MJ', 'LBJ', 'Shaq'], ['MJ', 'LBJ', 'Shaq'], ['MJ', 'LBJ', 'Shaq']]
但我想要的是:
[[[], [], []], [[], [], []], ['MJ', 'LBJ', 'Shaq']]
請問如何做到?([ [ [ ], [ ], [ ] ], [ [ ], [ ], [ ] ], [ [ ], [ ], [ ] ] ] 不切實際,如果要宣告大型串列根本打字打到死,我想要的是類似 C 語言 array[n][m] 的做法,再拜託各位大神了!)
python 的 list 是動態的
可以不用像 C 語言那樣一開始就宣告大小
利用 appned 可以把元素添加到最後
YogaTeacher = ("Kino", "Laruga", "DanySa")
BasketballPlayer = ["MJ", "LBJ", "Shaq"]
temp = []
for i,j in enumerate (YogaTeacher):
students = []
for k, l in enumerate (BasketballPlayer):
if (j == "DanySa"):
students.append(l)
else:
# 不知道為什麼你要空陣列
students.append([])
temp.append(students)
print (temp)
YogaTeacher = ("Kino", "Laruga", "DanySa")
BasketballPlayer = ["MJ", "LBJ", "Shaq"]
# 初始化 temp 為三個獨立的子列表,每個子列表包含三個空列表
temp = [[[] for _ in range(3)] for _ in range(3)]
print("初始化 temp:")
print(temp)
print()
for i, j in enumerate(YogaTeacher):
if j == "DanySa":
for k, l in enumerate(BasketballPlayer):
temp[i][k] = l
print("更新後的 temp:")
print(temp)
感謝三位大神,大家都回答得非常好,弱弱的我真是長知識了,最後我是採取 force 的做法,程式碼如下:
YogaTeacher = ("Kino", "Laruga", "DanySa")
BasketballPlayer = ["MJ", "LBJ", "Shaq"]
temp = [list (list () for i in range (3) ) for j in range (3)]
for i in range (len (BasketballPlayer)):
temp [YogaTeacher.index ("DanySa")][i] = BasketballPlayer[i]
print (temp)
站在巨人的肩膀上看得比較遠,希望我能實現我的夢想!