У меня есть следующий список:
Код: Выделить всё
list = [
[2, 'A', '1'],
[6, 'A', '2'],
[6, 'S', '3'],
[9, 'A', '4'],
[6, 'A', '5'],
[6, 'A', '6'],
[6, 'S', '7'],
[9, 'A', '8'],
[9, 'A', '9'],
[6, 'A', '10'],
[10, 'S', '11'],
[13, 'S', '12'],
[13, 'S', '13'],
[16, 'A', '14']
]
I need to concatenate all values that have a higher level than before (i-1). I can have multiple A and S in each level, but every time I find a S type I need to still search until I find a higher level of S or A type. My desired output:
Код: Выделить всё
['1.2', '1.3.4', '1.5', '1.6', '1.7.8', '1.7.9', '1.10.11.13.14']
Код: Выделить всё
def concat_levels(levels):
result = []
stack = []
for level in levels:
num, typ, name = level
while stack and stack [-1][0] >= num:
stack.pop()
if typ == 'A':
stack.append((num,name))
elif typ == 'S':
if stack:
current_path = '.'.join([x[1] for x in stack])
result.append(current_path + '.' + name)
return result
Код: Выделить всё
['1.3', '1.7', '1.10.11', '1.10.12', '1.10.13']
Код: Выделить всё
type == 'S'CONTEXT: This list is an abstracted version of a pyspark dataframe schema where A represents array type and S represents Structure type. Why 12 is not in the output? Because 12 is a struct (S type). It’s 1.10.11.13.14 Because the level 16 represents that value 14 is inside the value and level 13 structure. Since the schema is ordered, every time there is two S types in the same level, if an A type appears after a S type, then the last S type should be considered (always respecting the level rule)
Источник: https://stackoverflow.com/questions/781 ... -on-a-list