Python:从另一个lis填充列表

2024-06-28 20:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个新的列表(“新列表”),从现有的项目列表(“字母列表”)。 关键在于,新列表可以从现有列表中的任何项开始,具体取决于传递给函数(“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]


Tags: 项目函数in列表for参数indexif
2条回答

使用.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"))

不能将“按索引”分配给尚不存在的列表索引:

>>> 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结果:

^{pr2}$

下面是一个更具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

相关问题 更多 >