创建“反转"广告素材的最佳方法在Python中列出?

编程入门 行业动态 更新时间:2024-10-09 20:29:55
本文介绍了创建“反转"广告素材的最佳方法在Python中列出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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中列出?

本文发布于:2023-11-28 06:35:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641312.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:素材   方法   广告   quot   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!