我有一个txt文件,其中包含两个电话号码的列表以及两个号码之间的持续时间,如下所示:
3058 1234 2:28
1650 00777666555 2:03
3928 00423775651 4:54
2222 3333 5:20
3058 00876543210 1:49
3058 1234 1:15
1650 00876543210 2:10
2222 1234 2:32
3928 00172839456 1:38
1111 00969633330 3:01
我已经编写了一个函数来分割数字和时间,并计算它们的价格:
def getSec(time):
#change minute to second
min, sec = time.split(':')
return int(min) * 60 + int(sec)
def calPrice():
f = open('calls.txt', 'r')
print(f.read() + '\n')
with open('calls.txt') as file:
lines = file.readlines()
for line in lines:
anotherLineVar = line.split(' ')
firstNumb = anotherLineVar[0]
# print(firstNumb)
secNumb = anotherLineVar[1]
#print(secNumb)
time = anotherLineVar[2]
#print(time)
if int(secNumb[0]) == 0:
second = getSec(time)
price = second * 1.50
calPrice()
最后一步是,如果任何呼叫包含以00
开头的第二个号码,我需要向呼叫号码收取一些费用。我需要在列表中添加收费号码和价格。例如1650 00777666555 2:03
和3928 00423775651 4:54
的调用将收取184.5
和441.0
的费用,因此字典将显示为:
{1650:148.5
3928:441.0}
我试着做一些类似的事情
#outside the if statement
dict = {}
#inside the if statement
dict[secNumb] = price
print(dict)
但结果却是一团糟:
{'00777666555': 184.5}
{'00777666555': 184.5, '00423775651': 441.0}
{'00777666555': 184.5, '00423775651': 441.0, '00876543210': 163.5}
{'00777666555': 184.5, '00423775651': 441.0, '00876543210': 195.0}
{'00777666555': 184.5, '00423775651': 441.0, '00876543210': 195.0, '00172839456': 147.0}
{'00777666555': 184.5, '00423775651': 441.0, '00876543210': 195.0, '00172839456': 147.0, '00969633330': 271.5}
看起来您想用作dict
firstNumb
变量的键:在dict中,如果希望键是数字,则必须将它们从字符串转换为数字。因为您希望第一个数字作为dict中的键,所以在dict中按它时将其指定为键
试试这个
相关问题 更多 >
编程相关推荐