我需要根据俱乐部的号码按顺序输出这些押金。看一看第一项存款(0434512)。前两位数表示俱乐部号(在本例中是俱乐部号04)。其余数字代表存入帐户(34512)的存款。这需要四舍五入,所以应该输出为4,345.12美元。
deposits = ["0434512", "03145234", "012341347", "0511112345", "0475746","03654534", "02112"]
deposits.sort()
for i in deposits:
print i[1],
print int(i[2:])/100.
1 23413.47
2 1.12
3 1452.34
3 6545.34
4 345.12
4 757.46
5 111123.45我以为我已经完成了这件事,但事实证明,我需要把押金加到同一个俱乐部。所以我需要把1452.34和6545.34加在一起,和4号俱乐部一样。
提前感谢!
发布于 2016-04-06 18:23:46
你可以用字典:
deposits = ["0434512", "03145234", "012341347", "0511112345", "0475746","03654534", "02112"]
deposits.sort()
from collections import OrderedDict
mydict = OrderedDict()
for i in deposits:
mydict[i[:2]] = 0
for i in deposits:
mydict[i[:2]] += float(i[2:])/100输出:
>>> for i,j in mydict.items():
print(i,j)
01 23413.47
02 1.12
03 7997.68
04 1102.58
05 111123.45Python 2:
>>> for i,j in mydict.iteritems():
print i,j
01 23413.47
02 1.12
03 7997.68
04 1102.58
05 111123.45OrderedDict是用来保持俱乐部的数量顺序的。
以下是您可能感兴趣的一些链接:字典、OrderedDict
mydict = OrderedDict创建一个名为mydict的有序字典。
for i in deposits:
mydict[i[:2]] = 0然后,这个for循环使用deposits中每个条目中的前2个字符创建一个键。也就是俱乐部号码。它为每个俱乐部提供了一个0的值。
for i in deposits:
mydict[i[:2]] += float(i[2:])/100第二个for循环通过deposits并将第二个字符之后的所有内容添加到相应键的mydict值中。这仅仅是因为字典不能有两个同名的键。
我希望这能帮你理解。一旦你了解了字典是如何工作的,这就比较简单了。
发布于 2016-04-06 18:15:01
永远不要用列表来做字典的工作:
dictionary_repr = {}
for item in deposits:
if item in dictionary_repr:
# clump the clubs earnings to gain total earnings
dictionary_repr[int(item[1])] += int(item[2:]/100.00)
else:
# create the first instance of earnings
dictionary_repr[int(item[1])] = int(item[2:]/100.00)现在,您只需遍历字典并打印结果:
for club, amount in dictionary_repr.items(): # or iteritems in Py 2.7
print(club, amount) # or print club, amount in Py 2.7 发布于 2016-04-06 18:15:53
我认为您应该将您的俱乐部编号转换为int,但基于代码的解决方案可以如下所示
from collections import defaultdict
deposits = ["0434512", "03145234", "012341347", "0511112345", "0475746", "03654534", "02112"]
summary = defaultdict(float)
for i in deposits:
summary[i[:2]] += int(i[2:])/100.
#sort by club number
sorted_summary = sorted(summary.items(), key=lambda item: item[0])
for key, value in sorted_summary:
print key, value
#1 23413.47
#2 1.12
#3 7997.68
#4 1102.58
#5 111123.45https://stackoverflow.com/questions/36458746
复制相似问题