我有一個串列,如下所示
lst1 = [['sg'], ['sci'], ['op1', 'op2', 'op3'], ['pop1', 'pop2', 'pop3'], ['pn'], [['on'], ['pcat1', 'pcat2', 'pcat3'], ['oci']]]
我想遍歷這個串列串列(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')]
解釋:
- lst1 的第一個元素是主元素。每個元組都會在那里。
- 如果元素是具有一個元素的串列(如 ['sci']),則將其添加主元素并形成組(如 [('sg', 'sci')])
- 如果 lst1 的元素是具有多個值但不是嵌套串列的串列(如 ['op1', 'op2', 'op3']),則每個元素將形成一個組(如 [('sg', ' op1'), ('sg', 'op1', 'op2'), ('sg', 'op1', 'op2', 'op3')])。
- 如果 lst1 的元素是串列串列(如 [['on'], ['pcat1', 'pcat2', 'pcat3'], ['oci']]),那么它被展平并形成一個組(如[('sg', 'on', 'pcat1', 'pcat2', 'pcat3', 'oci')]) 和上述所有其他單個組(如 [('sg', 'on'), (' sg', 'pcat1'), ('sg', 'pcat1', 'pcat2'), ('sg', 'pcat1', 'pcat2', 'pcat3'), ('sg', 'oci')] )
uj5u.com熱心網友回復:
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))
編輯:實際上,如果您希望 ['sg'] 位于最前面,那么您的規范最后會要求 output=master output。
uj5u.com熱心網友回復:
如果結構只是一個描述,即沒有更深的層次等,那么你可以試試這個:
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)
結果 - 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')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/348939.html
上一篇:不知道如何編輯溢位的串列項
下一篇:索引和切片多維串列
