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 = ["big dog", "small dog", "medium dog"]
Thank you in advance!
You can sort by the position in the sentence by using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.