如何在每次出现特定元素时按字母顺序排列列表元素?

2024-05-18 10:53:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在这个具体问题上研究了几个小时了,还没有想出什么好办法

假设我有:

a = ['ot=apple', 'zz=top', 'par=four', 'xyz_test=wff', 'sesh=232d23f23f33ff', 
     '\n', 'xt=cal', 'poss=33', '\n', 'val=fifty', 'dvx=32f23f2', 
     '\n','dsfad=www', 'orr=dsav']

b = '\n'

我如何按字母顺序对ab的每一次出现之间进行排序

即,如何返回:

a = ['ot=apple', 'par=four', 'sesh=232d23f23f33ff','xyz_test=wff', 'zz=top', 
     '\n', 'poss=33','xt=cal', '\n', 'dvx=32f23f2','val=fifty', 
     '\n','dsfad=www', 'orr=dsav']

我成功地使用了:

    e_ = 0
    while e_ < len(new_list):
        new_list[e_] = sorted(new_list[e_], key=str.lower)
        e_ = e_+1

对其他列表进行排序,但我不确定在这种情况下如何进行排序,这种情况取决于'\n'的出现


Tags: testapplenew排序topotlistcal
2条回答

您可以将一维列表拆分为列表列表-每次发生'\n'时,启动一个新的内部列表-然后对内部列表进行排序并重新组合:

a = ['ot=apple', 'zz=top', 'par=four', 'xyz_test=wff', 'sesh=232d23f23f33ff', 
     '\n', 'xt=cal', 'poss=33', '\n', 'val=fifty', 'dvx=32f23f2', 
     '\n','dsfad=www', 'orr=dsav']

b = '\n'

# partition your data into sublists
stacked = [[]]
for k in a:
    if k == b:
        stacked.append([])
    else:
        stacked[-1].append(k)

# remove empty list at end if present
if not stacked[-1]:
    stacked = stacked[:-1]

# sort each inner list
for sublist in stacked:
    sublist.sort()

# unstack again
retval = []
for k in stacked:
    retval.append(b) # add a \n
    retval.extend(k) # extend with the sublist

# remove the first \n
retval = retval[1:]

print a 
print stacked 
print retval 

输出:

# a
['ot=apple', 'zz=top', 'par=four', 'xyz_test=wff', 'sesh=232d23f23f33ff', '\n', 'xt=cal', 
 'poss=33', '\n', 'val=fifty', 'dvx=32f23f2', '\n', 'dsfad=www', 'orr=dsav']

# stacked 
[['ot=apple', 'par=four', 'sesh=232d23f23f33ff', 'xyz_test=wff', 'zz=top'], ['poss=33', 'xt=cal'], 
 ['dvx=32f23f2', 'val=fifty'], ['dsfad=www', 'orr=dsav']]

# retval
['ot=apple', 'par=four', 'sesh=232d23f23f33ff', 'xyz_test=wff', 'zz=top', '\n', 
 'poss=33', 'xt=cal', '\n', 'dvx=32f23f2', 'val=fifty', '\n', 'dsfad=www', 'orr=dsav']
# create sublist
c = []
temp = []

for aa in a:
    if aa != b:
        temp += [aa]
    else:
        c += [temp]
        temp = []
        c += [b]
#sort and unravel
c = [sorted(i) for i in c]
d = [j for i in c for j in i]

print(d)
['ot=apple',
 'par=four',
 'sesh=232d23f23f33ff',
 'xyz_test=wff',
 'zz=top',
 '\n',
 'poss=33',
 'xt=cal',
 '\n',
 'dvx=32f23f2',
 'val=fifty',
 '\n']

相关问题 更多 >