簡體   English   中英

排列在Python中給定的句子/字符串中單詞排在第一位的列表

[英]Arrange list by which word comes first in given sentence/string in Python

我需要代碼按照它們在字符串(句子)中出現的順序對(單詞)列表進行排序。

例如:

list = ["small dog", "big dog", "medium dog"]

sentence = "Jack has a big dog not a small dog or medium dog."

然后,預期的new_list將是:

new_list = ["big dog", "small dog", "medium dog"]

先感謝您!

您可以使用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']

確實不希望對變量使用內置名稱,例如listdictset

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM