Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:从另一个列表填充列表_Python_List - Fatal编程技术网

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

Python:从另一个列表填充列表,python,list,Python,List,我正在尝试从现有列表(“字母列表”)中创建一个新列表(“新列表”)。 关键是,新列表可以从现有列表中的任何项开始,具体取决于传递给函数的参数(“firstLetter”): makeNewList(“B”) 我希望这会给我一个新的列表[“B”,“C”,“A”,“B”,“C”,“A”,“B”,“C”,“A”]但是我得到了 索引器:列表分配索引超出范围 参考此行:newList[j]=letterList[index]使用.append功能添加到列表末尾 def makeNewList(firstL

我正在尝试从现有列表(“字母列表”)中创建一个新列表(“新列表”)。 关键是,新列表可以从现有列表中的任何项开始,具体取决于传递给函数的参数(“firstLetter”):

makeNewList(“B”)

我希望这会给我一个新的列表[“B”,“C”,“A”,“B”,“C”,“A”,“B”,“C”,“A”]但是我得到了 索引器:列表分配索引超出范围
参考此行:newList[j]=letterList[index]

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