Python:从另一个列表中填写列表

时间:2014-09-04 16:48:20

标签: python list

我正在尝试从现有列表(“letterList”)的项目创建新列表(“newList”)。 问题是,新列表可以从现有列表中的任何项开始,具体取决于传递给函数的参数(“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”)

我希望这会给我newList [“B”,“C”,“A”,“B”,“C”,“A”,“B”,“C”,“A”]但是我得到    IndexError:列表赋值索引超出范围 引用此行:newList [j] = letterList [index]

3 个答案:

答案 0 :(得分: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"))

答案 1 :(得分: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

这是更多Pythonic实现:

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

答案 2 :(得分:0)

更多pythonic方法

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))