简体   繁体   中英

Python lists: join list by index

I'd like to join a list into a string by index in Python 3.3. I can do it for items the follow each other, but I would like to access it by index only.

this works:

list = ['A', 'B', 'C', 'D']
partList = "".join(list[1:3])
-> BC

But how can I achieve this (it doesn't work):

list = ['A', 'B', 'C', 'D']
partList = "".join(list[0,3])
-> AD

You can't slice lists into arbitrary chunks using slice notation . Probably your best bet for the general case is to use a list of indices to build a list comprehension.

mylist = ['A', 'B', 'C', 'D'] # the full list
indices = [0, 3] # the indices of myList that you want to extract

# Now build and join a new list comprehension using only those indices.
partList = "".join([e for i, e in enumerate(mylist) if i in indices])
print(partList) # >>> AD

As pointed out in the comments by DSM , if you're concerned with efficiency and you know your list of indices will be "friendly" (that is, it won't have any indices too big for the list you're cutting up), you can use a simpler expression without enumerate :

partList = "".join([mylist[i] for i in indices])

What you are intending to perform is not slicing but selecting.

The closest possibility, I can think of is to use operator.itemgetter

>>> from operator import itemgetter
>>> mylist = ['A', 'B', 'C', 'D']
>>> ''.join(itemgetter(0,3)(mylist))
'AD'

If you need to use a variable, then use a splat operator

index = (0,3)
''.join(itemgetter(*index)(mylist))

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