简体   繁体   English

根据单独列表中的 substring 对 python 列表进行排序

[英]Sort python list based on substring in separate list

I have 2 lists..我有2个清单..

list_a = ['Grapes/testfile.csv','Apples/testfile.csv','Pears/testfile.csv','Pears/testfile2.csv']
ref_list = ['Pears','Grapes','Apples']

I need to use ref_list list to order list_a .我需要使用ref_list list 来订购list_a

More context, list_a will always have the string from ref_list before the / but the length of ref_list will never match that of list_a .. Also I dont want to order reverse alphabetically.更多上下文, list_a将始终在/之前具有来自ref_list的字符串,但list_a的长度永远不会与ref_list的长度匹配。我也不想按字母顺序倒序。

Expected Output:预期 Output:

ordered_list = ['Pears/testfile.csv','Pears/testfile2.csv','Grapes/testfile.csv','Apples/testfile.csv']

I've tried many variations, referencing SO but I cant get this to work.. I just cant work out a way to reference the first list here is my attempt which obviously doesn't work as its not referencing ref_list but my logic is to use string method startswith()我尝试了很多变体,引用了 SO,但我无法让它工作.. 我只是想不出一种方法来引用第一个列表,这是我的尝试,它显然不起作用,因为它不引用ref_list但我的逻辑是使用字符串方法startswith()

Something like:?就像是:?

ordered_list = sorted(list_a, key = lambda x: x.startswith())

Use split() to extract the word before / .使用split()提取/之前的单词。

Then use index() to get the position of the starting word in ref_list , and use that for the sorting key.然后使用index()获取 ref_list 中起始词的ref_list ,并将其用作排序键。

ordered_list = sorted(list_a, key = lambda x: ref_list.index(x.split('/')[0]))

This answer may not be the most elegant, but it works:这个答案可能不是最优雅的,但它有效:

sorted_list = list()

for key in ref_list:

sorted_list += [sorted_value for sorted_value in list_a if \

sorted_value.startswith(key)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM