我正在尝试从我拥有的字符串列表中提取价格。
这些是 PriceList 的示例:
PriceList = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
'Daily:$1,800.00\n\nWeekend:$2200.00',
'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']
我想从 PriceList 中提取 MonthlyPrice 和 DailyPrice。
如果 MonthlyPrice 不存在,则它是 NA。
我试过这段代码:
for item in PriceList:
if item.find("Monthly")!= -1:
MonthlyPrice = (item[8:])
if item.find("Yearly")!= -1:
YearlyPrice = (item[7:])
if item.find("Weekly")!= -1:
WeeklyPrice = (item[7:])
但它不起作用,请帮我解决这个问题。
预期结果
print(WeeklyPrice) 列表中的第一个示例将为您提供 $3600.00
列表中第一个示例的 print(DailyPrice) 将为您提供 - NA。
请您参考如下方法:
与其笨拙地解析包裹在列表中的那个孤独的字符串,不如构建一个字典。
>>> prices = ['Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00']
>>> prices = dict(time_price.split(':') for time_price in prices[0].split())
>>> prices
{'Monthly': '$33,600.00', 'Daily': '$3,000.00', 'Weekly': '$8,400.00'}
从这里提取您想要的任何东西就像 child 的游戏一样。
>>> prices['Daily']
'$3,000.00'
>>> prices.get('NotFound', 'NA')
'NA'
请注意,如果您打算在未来对价格进行任何算术运算,将它们转换为 float 值是个好主意。
>>> prices = {k:float(v[1:].replace(',', '')) for k,v in prices.items()}
>>> prices
{'Monthly': 33600.0, 'Daily': 3000.0, 'Weekly': 8400.0}
