【发布时间】:2021-02-08 02:50:43
【问题描述】:
我必须对字符串中的关键字和值进行排序。
这是我的尝试:
import re
phrase='$1000 is the price of the car, it is 10 years old. And this sandwish cost me 10.34£'
list1 = (re.findall('\d*\.?\d+', phrase)) #this is to make a list that find all the ints in my phrase and sort them (1000, 10, 10.34)
list2= ['car', 'year', 'sandwish'] #this is to make a list of all the keywords in the phrase I need to find.
joinedlist = list1 + list2 #This is the combination of the 2 lists int and str that are in my sentence (the key elements)
filter1 = (sorted(joinedlist, key=phrase.find)) #This is to find all the key elements in my phrase and sort them by order of appearance.
print(filter1)
不幸的是,在某些情况下,因为“sorted”函数通过词法排序工作,积分会以错误的顺序打印。这意味着在某些情况下,像这种情况,输出将是:
['1000', '10', 'car', 'year', 'sandwich', '10.34']
代替:
['1000', 'car', '10', 'year', 'sandwich', '10.34']
因为汽车在初始短语中出现在 10 之前。
【问题讨论】:
-
你得到你看到的输出的原因是
1000和10出现在phrase的同一个地方,所以在filter1中是第一个。
标签: python string list sorting integer