Python:从另一个列表填充列表

0 投票
2 回答
3957 浏览
提问于 2025-04-19 20:53

我想从一个已有的列表(叫做“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: list assignment index out of range,错误出现在这一行:newList[j]=letterList[index]

2 个回答

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

你不能给一个还不存在的列表索引赋值:

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

相反,你应该用 append 方法把内容加到 newList 的末尾。另外,你还需要 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

撰写回答