python - 如何将日期字符串转换为数字
问题描述
我有输入:
["3 years 8 months", "10 months", "1 year 10 months", "9 months", " 1 month ", "1 year", "3 years"]
我想要这个输出:
[3.8, 0.10, 1.10, 0.09, 0.01, 1, 3]
解决方案
您可以使用str.split
:
def to_num(s):
c = {'year':1, 'years':1, 'month':0.01, 'months':0.01}
return sum(int(s[i])*c[s[i+1]] for i in range(0, len(s), 2))
vals = ["3 years 8 months", "10 months", "1 year 10 months", "9 months", "1 month", "1 year", "3 years"]
result = [to_num(i.split()) for i in vals]
输出:
[3.08, 0.1, 1.1, 0.09, 0.01, 1, 3]
推荐阅读
- flask - IIS 上未提供 Flask 静态文件夹
- apache-spark - 仅获取另一个数据框中存在列子集的数据框行
- python - Windows 命令提示符 ImportError 中的 Python Pandas:无法导入所需的依赖项:numpy (Anaconda)
- flutter - 如何更新屏幕上的目录文件?
- java - 如何将数据从广播接收器传递到 Android 中的活动
- c++ - find(vector.begin(),vector.end(), A[i])==vector.end() 的工作
- javascript - Express.js - 我无法设置 Content-Type
- java - 用于跨多个服务填充对象数据的设计模式
- go - 从 DynamoDB 获取项目时如何配置超时
- flutter - 待办事项列表的问题