如何在Python中的一行中追加多个项目

wha*_*ver 85 python

我有:

count = 0
i = 0
while count < len(mylist):
    if mylist[i + 1] == mylist[i + 13] and mylist[i + 2] == mylist[i + 14]:
        print mylist[i + 1], mylist[i + 2]
    newlist.append(mylist[i + 1])
    newlist.append(mylist[i + 2])
    newlist.append(mylist[i + 7])
    newlist.append(mylist[i + 8])
    newlist.append(mylist[i + 9])
    newlist.append(mylist[i + 10])
    newlist.append(mylist[i + 13])
    newlist.append(mylist[i + 14])
    newlist.append(mylist[i + 19])
    newlist.append(mylist[i + 20])
    newlist.append(mylist[i + 21])
    newlist.append(mylist[i + 22])
    count = count + 1
    i = i + 12
Run Code Online (Sandbox Code Playgroud)

我想把这些newlist.append()陈述变成几个陈述.

Ign*_*ams 209

不是.附加整个序列的方法是list.extend().

>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)


Kar*_*tel 5

没有.

首先,append是一个函数,所以你不能写,append[i+1:i+4]因为你试图获得一个不是序列的东西片.(你不能得到它的一个元素:append[i+1]出于同样的原因是错误的.)当你调用一个函数时,参数在括号中,即圆形的:().

其次,你要做的是"接受一个序列,并按照原始顺序将其中的每个元素放在另一个序列的末尾".这是拼写的extend.append是"拿这个东西,把它放在列表的末尾,作为单个项目,即使它也是一个列表 ".(回想一下列表是一种序列.)

但是,你需要知道这i+1:i+4是一个特殊的构造,它只出现在方括号内(从序列中得到一个切片)和大括号(用于创建一个dict对象).您无法将其传递给函数.所以你不能extend用那个.您需要创建这些值的序列,自然的方法是使用该range函数.


Kev*_*ite 5

您还可以:

newlist += mylist[i:i+22]
Run Code Online (Sandbox Code Playgroud)