简体   繁体   English

如果它的索引在另一个列表上,则从列表中获取项目

[英]Get an item from a list if its index is on another list

Well, I was looking on the site and I didn't find anything that could help me, so I came to ask.嗯,我在网站上看,我没有找到任何可以帮助我的东西,所以我来问了。 How do I get items from a list if its index is on another list ?如果它的索引在另一个列表中,我如何从列表中获取项目

Example:例子:

I have an array of vectors:我有一组向量:

[[0.0,0.0,0.1] [0.4,0.23,0.175] [0.0,1.,0.5] [0.0,0.03,0.1] [0.02,0.0,0.3]]

and a list of indices:和索引列表:

[0,2,3]

I want a result like this:我想要这样的结果:

[[0.0,0.0,0.1] [0.0,1.,0.5] [0.0,0.03,0.1]]

how can I get this result?我怎样才能得到这个结果? Grateful for any help :)感谢任何帮助:)

something like this像这样的东西

lst1 = [[0.0, 0.0, 0.1], [0.4, 0.23, 0.175], [0.0, 1., 0.5], [0.0, 0.03, 0.1], [0.02, 0.0, 0.3]]
lst2 = [0, 2, 3]
lst3 = [x for idx, x in enumerate(lst1) if idx in lst2]
print(lst3)

output输出

[[0.0, 0.0, 0.1], [0.0, 1.0, 0.5], [0.0, 0.03, 0.1]]

You can do this with a list comprehension.你可以通过列表理解来做到这一点。

For example:例如:

mylist = [[0.0,0.0,0.1], [0.4,0.23,0.175], [0.0,1.,0.5], [0.0,0.03,0.1], [0.02,0.0,0.3]]
indices = [0,2,3]
result = [mylist[i] for i in indices]

result is now [[0.0, 0.0, 0.1], [0.0, 1.0, 0.5], [0.0, 0.03, 0.1]]结果现在是[[0.0, 0.0, 0.1], [0.0, 1.0, 0.5], [0.0, 0.03, 0.1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM