我想從一個現有列表(「letterList」)的項目創建一個新列表(「newList」)。 美中不足的是,在新的列表可以在現有列表開始的任何項目,這取決於傳遞給函數(「firstLetter」)的說法:Python:從另一個列表填充列表
def makeNewList(firstLetter):
letterList=["A","B","C"]
newList=[]
# get index of argument (firstLetter)
for i in [i for i,x in enumerate(letterList) if x==firstLetter]:
index=i
# fill newList from cycling through letterList starting at index position
for j in range(10):
if index==3:
index=0
newList[j]=letterList[index]
index=index+1
makeNewList(「B」)
我希望這會給我newList [「B」,「C」,「A」,「B」,「C」,「A」,「B」,「C」,「A」]但我得到 IndexError :列表分配索引超出範圍 引用此行:newList [j] = letterList [index]