有两个清单:
A:[[0, 1, 3, 4, 6, 7], [2, 5]]
B:[(0, 5), (0, 9), (1, 7), (5, 0), (5, 9), (7, 1), (9, 0), (9, 5)]
A中的数字0, 1, 2, 3, 4, 5, 6, 7
对应
(0, 5), (0, 9), (1, 7), (5, 0), (5, 9), (7, 1), (9, 0), (9, 5)
是否有获取以下内容的快捷方式:
[[(0, 5), (0, 9), (5, 0), (5, 9), (9, 0), (9, 5)], [(1, 7),(7, 1)]]
代表A?
答案 0 :(得分:4)
使用operator.itemgetter
和列表理解,就像这样
>>> indexes = [[0, 1, 3, 4, 6, 7], [2, 5]]
>>> data = [(0, 5), (0, 9), (1, 7), (5, 0), (5, 9), (7, 1), (9, 0), (9, 5)]
>>> from operator import itemgetter
>>> [list(itemgetter(*item)(data)) for item in indexes]
[[(0, 5), (0, 9), (5, 0), (5, 9), (9, 0), (9, 5)], [(1, 7), (7, 1)]]
相反,你可以使用嵌套列表理解,就像这样
>>> [[data[index] for index in items] for items in indexes]
[[(0, 5), (0, 9), (5, 0), (5, 9), (9, 0), (9, 5)], [(1, 7), (7, 1)]]
答案 1 :(得分:2)
您可以简单地使用列表理解:
>>> A=[[0, 1, 3, 4, 6, 7], [2, 5]]
>>> B=[(0, 5), (0, 9), (1, 7), (5, 0), (5, 9), (7, 1), (9, 0), (9, 5)]
>>> C=[[B[i] for i in l] for l in A]
>>> C
[[(0, 5), (0, 9), (5, 0), (5, 9), (9, 0), (9, 5)], [(1, 7), (7, 1)]]
答案 2 :(得分:0)
是的,快捷方式是:
[[B[j] for j in i] for i in A]