2014-09-04 80 views
0

我想從一個現有列表(「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]

回答

1

使用.append函數添加到列表的末尾。

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.append(letterList[index]) 
     index=index+1 
    return newList 

print(makeNewList("B")) 
0

更Python的方法

from itertools import islice, cycle 
letterList=["A","B","C"] 
start=letterList.index('B') 
letterList = letterList[start:] + letterList[0:start] 
print list(islice(cycle(letterList), 10)) 
1

無法通過索引分配給尚不列表索引存在:

>>> l = [] 
>>> l[0] = "foo" 

Traceback (most recent call last): 
    File "<pyshell#25>", line 1, in <module> 
    l[0] = "foo" 
IndexError: list assignment index out of range 

相反,appendnewList結束。此外,您還需要return結果:

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.append(letterList[index]) # note here 
     index=index+1 

    return newList # and here 

這裏是一個更Python實現:

def make_new_list(first_letter, len_=10, letters="ABC"): 
    new_list = [] 
    start = letters.index(first_letter) 
    for i in range(start, start+len_): 
     new_list.append(letters[i % len(letters)]) 
    return new_list