繁体   English   中英

根据字符串中项目的出现对列表中的项目进行排序

[英]Sort items in the list based on the occurance of the item in a string

我是 python 的新手

我有一个这样的字符串和列表

s='''Hello, Carry out the item with care
Louis, MS to Dallas, TX '''
LOC=['Dallas','Louis']

如何根据字符串中单词的出现对列表进行排序?

所需的 Output:

LOC =['Louis','Dallas']

考虑到列表中的单词不会在字符串中重复多次。

您可以使用字符串的方法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.

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