我正在尝试创建一个新的列表(“新列表”),从现有的项目列表(“字母列表”)。 关键在于,新列表可以从现有列表中的任何项开始,具体取决于传递给函数(“firstLetter”)的参数:
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”)
我希望这会给我一个新的列表[“B”,“C”,“A”,“B”,“C”,“A”,“B”,“C”,“A”]但是我得到了 索引器错误:列表分配索引超出范围 引用此行:newList[j]=letterList[index]
使用
.append
函数添加到列表的末尾。在不能将“按索引”分配给尚不存在的列表索引:
相反,
^{pr2}$append
到newList
的结尾。另外,您需要return
结果:下面是一个更具python风格的实现:
相关问题 更多 >
编程相关推荐