gpt4 book ai didi

python - 如何使用 Python 中的索引列表获取列表切片?

转载 作者:行者123 更新时间:2023-11-28 19:44:30 25 4
gpt4 key购买 nike

在 Perl 中,我可以使用索引列表轻松地选择多个数组元素,例如

my @array = 1..11;
my @indexes = (0,3,10);
print "@array[ @indexes ]"; # 1 4 11

在 Python 中执行此操作的规范方法是什么?

最佳答案

使用operator.itemgetter:

from operator import itemgetter
array = range(1, 12)
indices = itemgetter(0, 3, 10)
print indices(array)
# (1, 4, 11)

然后根据需要呈现该元组...,例如:

print ' '.join(map(str, indices(array)))
# 1 4 11

关于python - 如何使用 Python 中的索引列表获取列表切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17126026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com