简体   繁体   中英

How to append multiple items in one line in Python

I have:

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

I wanted to make the newlist.append() statements into a few statements.

No. The method for appending an entire sequence is list.extend() .

>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]

No.

First off, append is a function, so you can't write append[i+1:i+4] because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either: append[i+1] is wrong for the same reason.) When you call a function, the argument goes in parentheses , ie the round ones: () .

Second, what you're trying to do is "take a sequence, and put every element in it at the end of this other sequence, in the original order". That's spelled extend . append is "take this thing, and put it at the end of the list, as a single item , even if it's also a list ". (Recall that a list is a kind of sequence.)

But then, you need to be aware that i+1:i+4 is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a dict object). You cannot pass it to a function. So you can't extend with that. You need to make a sequence of those values, and the natural way to do this is with the range function.

您还可以:

newlist += mylist[i:i+22]
mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

Use this :

#Inputs
L1 = [1, 2]
L2 = [3,4,5]

#Code
L1+L2

#Output
[1, 2, 3, 4, 5]

By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.

Happy Learning...:)

Use a for loop, it might look like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

If you are adding the same element then you can do the following:

["a"]*2
>>> ['a', 'a']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM