[英]Arrange list by which word comes first in given sentence/string in Python
I need the code to sort a list (of words) in the order by which they appear in a string (sentence). 我需要代码按照它们在字符串(句子)中出现的顺序对(单词)列表进行排序。
For example: 例如:
list = ["small dog", "big dog", "medium dog"]
sentence = "Jack has a big dog not a small dog or medium dog."
Then the expected new_list would be: 然后,预期的new_list将是:
new_list = ["big dog", "small dog", "medium dog"]
Thank you in advance! 先感谢您!
You can sort by the position in the sentence by using sorted
: 您可以使用sorted
句子中的位置进行sorted
:
_list = ['small dog', 'medium dog', 'big dog']
sentence = "Jack has a big dog not a small dog or medium dog."
new_list = sorted(_list, key=sentence.find)
['big dog', 'small dog', 'medium dog']
You really don't want to use built-in names for variables such as list
, dict
, set
, etc 您确实不希望对变量使用内置名称,例如list
, dict
, set
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.