在 Python 中,如何用另一个列表索引一个列表? [英] In Python, how do I index a list with another list?

查看:23
本文介绍了在 Python 中,如何用另一个列表索引一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用另一个这样的列表来索引一个列表

I would like to index a list with another list like this

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]

并且 T 最终应该是一个包含 ['a', 'd', 'h'] 的列表.

and T should end up being a list containing ['a', 'd', 'h'].

有没有比

T = []
for i in Idx:
    T.append(L[i])

print T
# Gives result ['a', 'd', 'h']

推荐答案

T = [L[i] for i in Idx]

这篇关于在 Python 中,如何用另一个列表索引一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆