如何从另一个列表的元素创建列表

请帮助我,我陷入了一些看起来很简单的事情。我只想从另一个列表的元素创建列表。我可以这样做,但无法找出更快的方法,因为我的列表有大约 500 个元素,我不想写 500 次列表名称。例子 :

testing = [ 'john', 'mark', 'joseph', 'cody', 'bill' , 'dick']
new= [testing [0], testing[3], testing[4]]

给了我我想要的,但我怎样才能让它更快。我试过

new = [testing ([0], [3], [4])]

并得到 'list' object is not callable

回答

对于不重写列表名称的具体情况

indices = [0, 3, 4]
new = [testing[i] for i in indices]

将工作。当你写

[testing ([0], [3], [4])]

你在写testing(...)。当 python 看到这些括号时,它认为你正在尝试调用一个函数,这就是为什么它说list object not callable.

还有像这样的切片符号

testing[a:b:step]

将元素从a直到(不包括)开始b,步长为step,但在您的情况下,您可能必须采用上面给出的更通用的方法,您只需自己提供索引。


以上是如何从另一个列表的元素创建列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>