【问题标题】:How to select multiple sets of elements from a list如何从列表中选择多组元素
【发布时间】:2021-12-28 04:56:21
【问题描述】:

我想根据一些索引从列表中选择多个包含三个或更多元素的组。

我想用itemgetter,但它不适用于多组,例如

labels=['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15']
indexlist = list(itertools.combinations(range(1, 10), 3))
ixs= [4,5]
a=[indexlist[ix] for ix in ixs]
from operator import itemgetter
print(*itemgetter(*a[0])(labels))

在哪里

a=[(1, 2, 7), (1, 2, 8)]

效果很好,而

labels=['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15']
indexlist = list(itertools.combinations(range(1, 10), 3))
ixs= [4,5]
a=[indexlist[ix] for ix in ixs]
from operator import itemgetter
print(*itemgetter(*a)(labels))

给出错误

list indices must be integers or slices, not list

有没有办法将多组索引传递给itemgetter,或者有其他方便的替代方法吗?

【问题讨论】:

    标签: python list indices


    【解决方案1】:

    如前所述,您正在尝试解析多个索引。为方便起见,您可以使用 numpy。

    labels = np.array(['C1','C2','C3','C4','C5','C6','C7','C8','C10','C13','C14','C15'])
    print([list(labels[index_tuples])] for index_tuples in a)
    

    这样做是使用您的元组获取多组索引并将它们打印为列表。

    来源:Access multiple elements of list knowing their index

    【讨论】:

    • 我不确定如何使用那个生成器,如果我询问list(labels[a[0]]) 我会得到IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed
    猜你喜欢
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多