简体   繁体   English

排列在Python中给定的句子/字符串中单词排在第一位的列表

[英]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 确实不希望对变量使用内置名称,例如listdictset

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 python 识别字符串中单词之后的分隔符 - How to identify which delimiter comes first after word in a string using python 在句子中查找单词并按顺序排列 - find word in sentence and arrange in sequence 在 Python 中查找具有给定单词的特定句子 - Find a specific sentence with a given word in Python 在python中将第一个单词添加到句子的最后一个 - Add first word to the last of a sentence in python 如何使用 ascii 分数和 python 中的序号 function 确定哪个单词按字母顺序排在第一位? - How to determine which word comes first in the alphabetical order using ascii score and the ord function in python? 获取列中给定的字符串的第一个字母(句子),并在python中创建一个新列 - get first letter of a String (sentence) given in a column and create a new column in python 在句子字符串中找到不同的单词实现 - Python - Find different realization of a word in a sentence string - Python Python正则表达式可查找以A或B结尾的字符串(无论A优先还是B优先)(非贪婪搜索) - Python regex to find string which ends with A OR B, either if A comes first or B (non-greedy search) Python:有没有找到哪个子串(来自一组子串)首先出现在字符串中的快捷方式? - Python: Is there a shortcut to finding which substring(from a set of substrings) comes first in a string? 找出:给定句子中一个字符中出现了多少个单词:PYTHON - find out: In how many word a character is present in a given Sentence: PYTHON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM