gpt4 book ai didi

Python 使用另一个列表迭代列表

转载 作者:行者123 更新时间:2023-12-02 16:37:10 25 4
gpt4 key购买 nike

我认为这很简单,但它不适合我。我有 2 个列表:

a = [1, 3, 6]
b = [['A', 'B', 'C', 'D', 'E', 'F', 'G'],
['H', 'I', 'J', 'K', 'L', 'M', 'N'],
['O', 'P', 'Q', 'R', 'S', 'T', 'U']]

我需要使用 a 的元素遍历 b。

期望的输出是:

c = [['B', 'D', 'G'],
['I', 'K', 'N'],
['P', 'R', 'U']]

欢迎使用数组,有什么建议吗?

最佳答案

您可以使用 itemgetter()来自内置的方法 operator模块:

from operator import itemgetter

a = itemgetter(1, 3, 6)

b = [['A', 'B', 'C', 'D', 'E', 'F', 'G'],
['H', 'I', 'J', 'K', 'L', 'M', 'N'],
['O', 'P', 'Q', 'R', 'S', 'T', 'U']]

c = [list(a(l)) for l in b]

print(c)

输出:

[['B', 'D', 'G'],
['I', 'K', 'N'],
['P', 'R', 'U']]

关于Python 使用另一个列表迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62457651/

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