[英]How to get rid of a word in a list of strings
Currently I am having this kind of a list:目前我有这样的清单:
['Rating 3.9577555469954', 'Rating 3.730694980695', 'Rating 4.0717869548437', 'Rating 4.0597014925373', 'Rating 3.7323798994975']
I am trying to get rid of the 'Rating ' part.我试图摆脱“评级”部分。 How do I achieve that in the end there are only numbers/floats in my list?
我如何最终实现我的列表中只有数字/浮点数?
An alternative to jordanm's answer using regex
:使用
regex
替代 jordanm 的答案:
import re
strings = ['Rating 3.9577555469954', 'Rating 3.730694980695', 'Rating 4.0717869548437', 'Rating 4.0597014925373', 'Rating 3.7323798994975']
floats = [float(re.findall('([0-9]+[,.]+[0-9]+)',x)[0]) for x in strings]
print(floats)
Outputs:输出:
[3.9577555469954, 3.730694980695, 4.0717869548437, 4.0597014925373, 3.7323798994975]
This will capture all digits, regardless of "Rating" or other word that might precede it.这将捕获所有数字,而不管它前面的“评级”或其他单词。 (in case there's
Ratings
for example) (例如,如果有
Ratings
)
Loop through list and strip the value.循环遍历列表并剥离值。 I like to use UPPER or LOWER to catch all cases.
我喜欢使用 UPPER 或 LOWER 来捕获所有情况。
my_list = ['Rating 3.9577555469954', 'Rating 3.730694980695',
'Rating 4.0717869548437', 'Rating 4.0597014925373', 'Rating 3.7323798994975']
new_list = []
for value in my_list:
new_list.append(value.upper().strip('RATING').strip())
print(new_list)
Results:结果:
['3.9577555469954', '3.730694980695', '4.0717869548437', '4.0597014925373', '3.7323798994975']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.