[英]Iterate over list of lists and deduce a final list so that group by can be done on each element of final list in python
I am having a list of lists like below我有一个列表,如下所示
lst1 = [['sg'], ['sci'], ['op1', 'op2', 'op3'], ['pop1', 'pop2', 'pop3'], ['pn'], [['on'], ['pcat1', 'pcat2', 'pcat3'], ['oci']]]
I want to iterate over this list of lists (lst1) and get the result like below list of tuples or list of lists我想遍历这个列表列表(lst1)并得到如下元组列表或列表列表的结果
[('sg',), ('sg', 'sci'), ('sg', 'op1'), ('sg', 'op1', 'op2'), ('sg', 'op1', 'op2', 'op3'), ('sg', 'pop1'), ('sg', 'pop1', 'pop2'), ('sg', 'pop1', 'pop2', 'pop3'), ('sg', 'pn'), ('sg', 'on', 'pcat1', 'pcat2', 'pcat3', 'oci'), ('sg', 'on'), ('sg', 'pcat1'), ('sg', 'pcat1', 'pcat2'), ('sg', 'pcat1', 'pcat2', 'pcat3'), ('sg', 'oci')]
Explanation:解释:
lst1 = [['sg'], ['sci'], ['op1', 'op2', 'op3'], ['pop1', 'pop2', 'pop3'], ['pn'], [['on'], ['pcat1', 'pcat2', 'pcat3'], ['oci']]]
master=lst1[0]
non_masters=lst1[1:]
def appendMasterSimple(item):
lists_to_return=[]
for i in range(0,len(item)):
lists_to_return.append(master+item[0:i+1])
return lists_to_return
def appendMasterEmbedded(item):
lists_to_return=[]
flat_list=[]
for sublist in item:
flat_list.extend(sublist)
lists_to_return.append(master+flat_list)
for sublist in item:
lists_to_return.extend(appendMasterSimple(sublist))
return lists_to_return
output=[]
for item in non_masters:
if type(item[0])==list:
output.extend(appendMasterEmbedded(item))
else:
output.extend(appendMasterSimple(item))
Edit: Actually your specs call for output=master+output at the very end if you want ['sg'] to be in the front.编辑:实际上,如果您希望 ['sg'] 位于最前面,那么您的规范最后会要求 output=master+output。
If the structure is just a described, ie there are no deeper levels etc., then you could try this:如果结构只是一个描述,即没有更深的层次等,那么你可以试试这个:
tree = [tuple(lst1[0])]
for sublist in lst1[1:]:
if all(isinstance(item, str) for item in sublist):
last = tree[0]
for item in sublist:
tree.append(last + (item,))
last = tree[-1]
else:
base = tree[0]
extension = []
for subsublist in sublist:
base = base + tuple(subsublist)
last = tree[0]
for item in subsublist:
extension.append(last + (item,))
last = extension[-1]
tree.append(base)
tree.extend(extension)
Result - tree
- for your sample:结果 -
tree
- 您的样本:
[('sg',),
('sg', 'sci'),
('sg', 'op1'),
('sg', 'op1', 'op2'),
('sg', 'op1', 'op2', 'op3'),
('sg', 'pop1'),
('sg', 'pop1', 'pop2'),
('sg', 'pop1', 'pop2', 'pop3'),
('sg', 'pn'),
('sg', 'on', 'pcat1', 'pcat2', 'pcat3', 'oci'),
('sg', 'on'),
('sg', 'pcat1'),
('sg', 'pcat1', 'pcat2'),
('sg', 'pcat1', 'pcat2', 'pcat3'),
('sg', 'oci')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.