如何将所有元素放入不同大小的子列表中?
我在a_list中有子列表:
a_list = [['a', 'b'], ['a', 'b'], ['a']]
我需要根据所有元素的索引对其进行分组,并且如果子列表缺少元素,则需要忽略所有元素。
这是我需要的输出:
['a', 'a', 'a']
['b', 'b'] # here's where I'm having problems
我试过了:
for index, a in enumerate(a_list):
another_list = (list(zip(*a_list))[index]) # IndexError
还尝试了:
another_list = list()
for index, a in enumerate(a_list):
another_list.append([x[index] for x in a_list]) # IndexError
这应该工作:
a_list = [['a', 'b'], ['a', 'b'], ['a']]
r = len(max(a_list, key=len))
z = [sum([x[i:i+1] for x in a_list], []) for i in range(r)]
z
>>> [['a', 'a', 'a'], ['b', 'b']]
说明:
让我们考虑您的第二次尝试:
another_list = list()
for index, a in enumerate(a_list):
another_list.append([x[index] for x in a_list]) # IndexError
此代码的问题是:
a_list
,而您应该遍历索引(我使用最长子列表的范围)x[index]
,而我使用时x[index:index+1]
,它将返回一个列表(如果索引超出范围,则为空)sum(index_group, [])
整理组(请参见下面的代码)然后在我的代码中将所有这些内容合并到一个列表理解中,但是下面可以for
像您一样使用循环找到等效的版本。
您的代码的修改后的版本:
a_list = [['a', 'b'], ['a', 'b'], ['a']]
another_list = list()
for index in range(max([len(x) for x in a_list])): # loop over indexes
# create a list of sublist slices containing the index-th element
ind_group = [x[index:index+1] for x in a_list]
# flatten the list
flat_ind_group = sum(ind_group, [])
another_list.append(flat_ind_group)
another_list
>>> [['a', 'a', 'a'], ['b', 'b']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句