1

我有一个包含元素的列表:

['16:11:40.894 0,Type=IsXover,Count=1,lp-isD=2'
 '16:11:40.894 0,Type=IsXover,Count=54,lp-xsD=1'
 '16:11:40.894 0,Type=IsXover,Count=201,lr-isD=3'
 '16:11:40.894 0,Type=IsXover,Count=3075,lp-gsD=5']

我想根据 'Count=' 之后的数字对这个列表进行排序。我不能像这里所说的那样使用 .sort(key=lambda x: x[37]) 来做到这一点 ,因为我的数字变成了两倍,三倍,...数字。如何在不使用正则表达式的情况下对该列表进行排序?

(请不要列表很长,我写了上面列表的摘要版本)

4

5 回答 5

2

这样做:

to_sort = ['16:11:40.894 0,Type=IsXover,Count=201,lr-isD=3',
           '16:11:40.894 0,Type=IsXover,Count=54,lp-xsD=1',
           '16:11:40.894 0,Type=IsXover,Count=1,lp-isD=2',
           '16:11:40.894 0,Type=IsXover,Count=3075,lp-gsD=5']
def key(x:str):
    return int(x.partition("Count=")[2].partition(",")[0])

print(sorted(to_sort, key=key))
于 2018-05-02T15:48:21.723 回答
0
lst = ['16:11:40.894 0,Type=IsXover,Count=1,lp-isD=2',
       '16:11:40.894 0,Type=IsXover,Count=54,lp-xsD=1',
       '16:11:40.894 0,Type=IsXover,Count=201,lr-isD=3',
       '16:11:40.894 0,Type=IsXover,Count=3075,lp-gsD=5']

def extract_num(text):
    txt1 = text[text.find("Count=")+6:]
    txt2 = txt1[:txt1.find(",")]
    return int(txt2)

lst.sort(key=extract_num)

print(lst)
于 2018-05-02T15:48:10.797 回答
0

如果没有正则表达式,并假设所有字符串的格式相同,您可以这样做:

mylist.sort(key = lambda x: int(''.join([i for i in x.split(',')[2] if i.isnumeric()])))

列表理解[i for i in x.split(',')[2] if i.isnumeric()]在逗号处拆分您的字符串,获取索引 2 处的元素(将是“ Count=___”),并提取所有数字字符串。然后,int(''.join将它们连接在一起并将其转换为整数。然后,您可以将其用作对列表进行排序的键。

于 2018-05-02T15:50:14.903 回答
0
lst = ['16:11:40.894 0,Type=IsXover,Count=1,lp-isD=2',
       '16:11:40.894 0,Type=IsXover,Count=54,lp-xsD=1',
       '16:11:40.894 0,Type=IsXover,Count=201,lr-isD=3',
       '16:11:40.894 0,Type=IsXover,Count=3075,lp-gsD=5']

count_dict = {}

for elem in lst:
    temp_list = elem.split(',')
    count = temp_list[2]

    new_count = int(count.split('=')[1])

    count_dict[new_count] = elem

new_list = []

for count in sorted(count_dict):
    new_list.append(count_dict[count])
于 2018-05-02T16:04:54.063 回答
0

您可以尝试Chris_Rands告诉的方法。

尝试通过拆分整个字符串来从字符串中提取 Count 参数的值。

sorted(lst, key=lambda x: int(x.split('Count=', 1)[1].split(',', 1)[0]))

上面的语句首先根据键 'Count=' 拆分字符串。所以之前的字符串部分可以忽略,因此我们使用索引 1 获取字符串的第二部分。在这部分中,我们再次将字符串拆分为“,”。然后忽略它之后的部分。所以我们只取','之前的部分,使用索引0。最后,我们将此值解析为整数类型。

For ex. take '16:11:40.894 0,Type=IsXover,Count=1,lp-isD=2'

after splitting the string from 'Count=' and taking the value at index 0, we get '1,lp-isD=2'.

now splitting this from ',' and taking the value at index 0, we get '1'.

So after parsing this to function int(), we get the value of Count.
于 2020-04-18T21:51:00.827 回答