【发布时间】:2021-02-11 10:01:12
【问题描述】:
我正在尝试根据嵌套索引从嵌套列表中获取输出列表。
输入:
list_a = [(a,b,c,d), (f,g), (n,p,x)]
sub_index_a = [(0,2),(1),(0,1)]
输出:
output_list = [(a,c), (g), (n,p)]
【问题讨论】:
标签: python list python-2.7 nested
我正在尝试根据嵌套索引从嵌套列表中获取输出列表。
输入:
list_a = [(a,b,c,d), (f,g), (n,p,x)]
sub_index_a = [(0,2),(1),(0,1)]
输出:
output_list = [(a,c), (g), (n,p)]
【问题讨论】:
标签: python list python-2.7 nested
使用zip 和嵌套推导:
list_a = [("a","b","c","d"), ("f","g"), ("n","p","x")]
sub_index_a = [(0,2),(1,),(0,1)] # note the comma in the second tuple
output_list = [tuple(sub[i] for i in i_s) for sub, i_s in zip(list_a, sub_index_a)]
# [('a', 'c'), ('g',), ('n', 'p')]
【讨论】:
("g") 的计算结果为 "g",实际元组看起来像 ("g",) (tuple(["g"])),与 (1) 相同,但我认为找到了一个不错的解决方法?希望这是您想要的解决方案。
list_a = [('a','b','c','d'), ('f','g'), ('n','p','x')]
sub_index_a = [(0,2),(1),(0,1)]
print([tuple([list_a[x][indx] for indx in i]) if type(i) in [tuple, list] else list_a[x][i] for x,i in enumerate(sub_index_a)])
[('a', 'c'), 'g', ('n', 'p')]
如果您希望将所有内容作为元组返回,您可以将理解修改为:
print([tuple([list_a[x][indx] for indx in i]) if type(i) in [tuple, list] else tuple([list_a[x][i]]) for x,i in enumerate(sub_index_a)])
[('a', 'c'), ('g',), ('n', 'p')]
注意:
如果您希望所有内容都嵌套(使用单个元素),您将需要一个列表列表;例如。
[[0,2],[1],[0,1]]
【讨论】:
list_a = [('a', 'b', 'c', 'd'), ('f', 'g'), ('n', 'p', 'x')]
sub_index_a = [(0, 2), (1,), (0, 1)]
def check(i, e):
r = []
for ee in e:
r.append(list_a[i][ee])
return tuple(r)
outputlist = [check(i, e) for i, e in enumerate(sub_index_a)]
print(outputlist)
计算结果为
[('a', 'c'), ('g',), ('n', 'p')]
【讨论】: