简体   繁体   中英

Appending to a List

L = ['abc', 'ADB', 'aBe']

L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...

... works, but 'a2' is missing in the output:

['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']

I think that the -1 is pointing at the last element of the list, which gets overwritten by 'a3'. As described here , you can do a

list.extend(['a3', 'a4'])

Use L.append (for a single element) or L.extend (for a sequence) -- there's absolutely no call for playing fancy "assign-to-slice" tricks (especially if you don't master them!-). The slice [-1:] means "last element included onwards" -- so, by assigning to that slice, you're obviously "overwriting" the last element!

What is wrong with:

L.append('a1')

or

L += ['a1', 'a2']

要将项目追加到列表中,可以使用+

L + ["a1","a2"]

Your 3rd assignment is overwriting the 'a2' value.

Perhaps you should be using a more straightforward method:

L = ['abc', 'ADB', 'aBe']
L += ['a1', 'a2']
L += ['a3', 'a4']
Etc.

Use the extend method

L = ['abc', 'ADB', 'aBe']
L.extend(['a1', 'a2'])
L.extend(['a3', 'a4'])

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