I have one list that I want to take a slice of, reverse that slice and append each of those items onto the end of another list. The following are the options I have thought of (although if you have others please share), which of these is the most pythonic?
# Option 1
tmp = color[-bits:]
tmp.reverse()
my_list.extend(tmp)
# Option 2
my_list.extend(list(reversed(color[-bits:])))
# Option 3
my_list.extend((color[-bits:])[::-1])
I like
my_list.extend(reversed(color[-bits:]))
It explains what you are doing ( extending a list by reverse of another list's slice) and is short too.
and a obligatory itertools solution
my_list.extend( itertools.islice( reversed(color), 0, bits))
my_list.extend(color[:-(bits + 1):-1])
For Option #2, you can cut out the call to list
. You could also use +=
instead of extend
, like so:
my_list += reversed(color[-bits:])
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.