[英]What is the most pythonic way to extend a list with the reversal of another?
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?
以下是我想到的选项(尽管如果您还有其他人也可以分享),那么哪个选项最适合python?
# 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 和强制性的itertools解决方案
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
. 对于选项2,您可以剪切对
list
的呼叫。 You could also use +=
instead of extend
, like so: 您也可以使用
+=
代替extend
,如下所示:
my_list += reversed(color[-bits:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.