我的文件discount.txt包含以下格式的数据:
Less than $100 --> 0%
From $100 up to less than $500 --> 10%
From $500 up to less than $1,000 --> $40 PLUS 20%
From $1,000 up to less than $2,000 --> $140 PLUS 30%
$2,000 and above --> $440 PLUS 40%
表示销售金额的折扣
Less than $100 0%
From $100 up to less than $500 10% for each dollar over $100
From $500 up to less than $1,000 $40 PLUS 20% of the total sale amount over $500
From $1,000 up to less than $2,000 $140 PLUS 30% of the total sale amount over $1,000
$2,000 and above $440 PLUS 40% of the total sale amount over $2,000
也就是说,如果总销售额为100美元,那么折扣将为0美元。但是,如果总销售额为101美元,那么折扣将为0.10美元。如果总销售额为500美元,那么折扣将为40美元,但如果总销售额为501美元,那么折扣将为40.20美元。
所以为了解决这个问题,我认为有4个清单:1个用于存储销售额下限的清单,一个用于存储上限,一个用于存储对应于范围的固定增量,一个用于存储额外折扣。如果没有固定的增量,则假设为零。
然后,对于给定的销售额,如果它位于第i个范围,那么只需执行以下操作:
fixedIncrement[i] + (saleAmount-lowerLimit[i])*additionDiscount[i]
但面临的问题是解析给定的文本文件。有人可以帮助解析它并将其存储在python中的列表中
在给定文件中,列表将是这样的:
lowerLimit[] = [1,100,500,1000,2000]
upperLimit[] = [100,500,1000,2000,MAX]
fixedIncrement[] = [0,0,40,140,440]
additionDiscount[] = [0,0.1,0.2,0.3,0.4]
答案 0 :(得分:0)
您可以采用以下方法:
lower_limit,upper_limit,fixed_increment,discount
1,100,0,0
100,500,0,0.1
500,1000,40,0.2
csv
模块读取文件并将值存储在相应的列表中。您可以在此处查看相关文档:Python docs 答案 1 :(得分:0)
打开.txt:
with open ("data.txt", "r") as myfile:
data=myfile.readlines()
每行应该是列表中的字符串,例如['string one',string two'] 将每个字符串转换为字符串列表
all_lines = [i.split() for i in data]
>>> all_lines = [['string', 'one'], ['string', 'two']]
for l in all_lines:
# Go through each line
从100美元到不到500美元 - > 10%转换为:
l = ['From', '$100', 'up', 'to', 'less', 'than', '$500', '-->', '10%']
现在你应该能够使用逻辑解析它了。例如,从该行获取范围参数:
all_ranges = []
r1 = [i for i in l if "$" in i]
if l[0] == 'From': # Contains a range
r = (int(r1[0][1:]), int(r1[1][1:]))
all_ranges.append(r)
print all_ranges
>>> [(100, 500)]
编辑:
elif l[0] == "Less": # No range in this line
r = (0, int(r1[0][1:])) # Range is from 0 to $100
all_ranges.append(r)
else:
top = l[0][1:]
all_ranges.append((top, 1000000)) # High range
>>>> [(100, 500), (0, 100), (2000, 1000000)]