python - 获取具有给定索引的 Python 列表的子列表?

标签 python list python-2.7

我有一个 Python 列表,比如 a = [0,1,2,3,4,5,6]。我还有一个索引列表,比如 b = [0,2,4,5]。如何在 b 中获取带有索引的 a 元素列表?

最佳答案

您可以使用 list comprehension 来获取该列表:

c = [a[index] for index in b]
print c

这相当于:

c= []
for index in b:
    c.append(a[index])
print c

输出:

[0,2,4,5]

注意:

请记住,some_list[index] 是用于访问特定索引中 list 元素的符号。

关于python - 获取具有给定索引的 Python 列表的子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22412509/

相关文章:

python - 使用嵌套列表理解提高执行速度

Python scikit学习MLPClassifier "hidden_layer_sizes"

python - tf.space_to_depth 有什么用?

python - setup.py、setup() 以及其他一些东西

python - pymysql.err.IntegrityError : (1062, "Duplicate entry ' 820 7' for key ' agentId'")

c# - 在多个线程中添加和删除时 List<string> 中的 null 值

python - 将 pandas 数据框打印为行长超过 80 个字符的文本

javascript - JS : name/val pairs to array

python - Tkinter - 添加滚动条时文本小部件缩小

Python Pandas.Series.asof : Cannot compare type 'Timestamp' with type 'struct_time'