python3.3嵌套列表中列的部分比较排序

2024-09-29 03:28:54 发布

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

我尝试对嵌套列表中的列进行排序,如下所示:

lst = [["1", "2", "3", "4"],
       ["some text 1", "some text 2", "some text 3", "some text 4"],
       ["some text", "some text to analyze with RZstring", "some RZ-text to analyze", "some text to analyze with no rz-string and no textRZ"]]

根据第3个嵌套列表的字符串中是否存在区分大小写的“RZ”前缀(带RZ的应位于底部):

lst = [["1", "4", "2", "3"],
       ["some text 1", "some text 4", "some text 2", "some text 3"],
       ["some text", "some text to analyze with no rz-string and no textRZ", "some text to analyze with RZstring", "some RZ-text to analyze"]]

我觉得应该有一些好的和简单的方法来使用itemgetterlambda函数,但是没有看到明显的解决方案。你知道吗


Tags: andtonotext列表string排序with
2条回答

首先,我要将三个列表转换为一个包含三个元组的列表:

newList = zip(*lst)

这会给你:

[("1", "some text", "some text"), ...]

您需要定义一个排序函数来编码您的RZ规则,但是排序很容易:

def sortFunc(item):
    # example, not sure what you need
    return item[2].lower().count("rz") 

sorted(newList, key=sortFunc)

你好像把两个问题混在一起了。第一种是对嵌套列表进行排序,第二种是如何根据这些RZ内容进行排序。你知道吗

您可以通过首先转置多维数组来执行前者,这样属于一起的项实际上在同一个子列表中。然后就可以根据第三个列表项上的排序函数进行排序。你知道吗

>>> list(zip(*sorted(zip(*lst), key=lambda x: x[2])))
[('3', '1', '2', '4'), ('some text 3', 'some text 1', 'some text 2', 'some text 4'), ('some RZ-text to analyze', 'some text', 'some text to analyze with RZstring', 'some text to analyze with no rz-string and no textRZ')]

不过,对于第二个问题,我不太明白这种排序是基于什么。如果它是RZ之前的前缀,那么后两项仍然会被颠倒,还是不会?你知道吗


根据注释中更新的规范,您可以使用正则表达式检查RZ是否出现在前面(\b)的单词边界处,并在排序键的from中添加该事实:

>>> import re
>>> list(zip(*sorted(zip(*lst), key=lambda x: (re.search(r'\bRZ', x[2]) != None, x[2]))))
[('1', '4', '3', '2'), ('some text 1', 'some text 4', 'some text 3', 'some text 2'), ('some text', 'some text to analyze with no rz-string and no textRZ', 'some RZ-text to analyze', 'some text to analyze with RZstring')]

相关问题 更多 >