[英]Sort items in the list based on the occurance of the item in a string
I am a newbie to python我是 python 的新手
I have a string and list like this我有一个这样的字符串和列表
s='''Hello, Carry out the item with care
Louis, MS to Dallas, TX '''
LOC=['Dallas','Louis']
How to sort the list according to the occurrence of the word from a string?如何根据字符串中单词的出现对列表进行排序?
Desired Output:所需的 Output:
LOC =['Louis','Dallas']
Considering the word in the list doesn't repeat multiple times in the string.考虑到列表中的单词不会在字符串中重复多次。
You can use the method index
of strings to find the position of the occurrence, then do a sort
of that list based on that, for example:您可以使用字符串的方法index
查找出现的 position,然后根据该列表进行sort
,例如:
s = '''Hello, Carry out the item with care
Louis, MS to Dallas, TX '''
LOC = ['Dallas', 'Louis', 'TX', 'out']
sorted_LOC = sorted(LOC, key=s.index)
print(sorted_LOC)
>>> ['out', 'Louis', 'Dallas', 'TX']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.