在Python中,创建一个与其他列表的项目相同但顺序相反的新列表的最佳方法是什么? (我不想就地修改现有列表.)
In Python, what is the best way to create a new list whose items are the same as those of some other list, but in reverse order? (I don't want to modify the existing list in place.)
这是我想到的一种解决方法:
Here is one solution that has occurred to me:
new_list = list(reversed(old_list))也可以复制old_list,然后在原处反向复制:
It's also possible to duplicate old_list then reverse the duplicate in place:
new_list = list(old_list) # or `new_list = old_list[:]` new_list.reverse()是否有我忽略的更好的选择?如果没有,那么是否有令人信服的理由(例如效率)来使用上述一种方法而不是另一种方法?
Is there a better option that I've overlooked? If not, is there a compelling reason (such as efficiency) to use one of the above approaches over the other?
推荐答案newlist = oldlist[::-1]
[::-1]切片(我的妻子安娜喜欢称其为火星人的笑脸" ;-)的意思是:以-1的步长(即相反)对整个序列进行切片.它适用于所有序列.
The [::-1] slicing (which my wife Anna likes to call "the Martian smiley";-) means: slice the whole sequence, with a step of -1, i.e., in reverse. It works for all sequences.
请注意,此(您提到的和替代方案)等效于浅表副本",即:如果项目是可变的,并且您将其称为变种子,则保留在项目中的变种原始列表也位于反向列表的项目中,反之亦然.如果您需要避免这种情况,那么copy.deepcopy(尽管总是很昂贵的操作),然后再加上.reverse,是唯一的好选择.
Note that this (and the alternatives you mentioned) is equivalent to a "shallow copy", i.e.: if the items are mutable and you call mutators on them, the mutations in the items held in the original list are also in the items in the reversed list, and vice versa. If you need to avoid that, a copy.deepcopy (while always a potentially costly operation), followed in this case by a .reverse, is the only good option.
更多推荐
创建“反转"广告素材的最佳方法在Python中列出?
发布评论