我正在尝试打印出一个字典(实际上是 a defaultdict
),其中键是版本号(形式为6.0
or 6.1.2
),值是浮点数。
# Parse file contents
firmware_percents = defaultdict(float)
with open('test.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
# Don't care about iphone vs ipad
# Must be a string - StrictVersion is apparently unhashable
rev = row["Firmware Version"].split(" ")[2]
# Dump extra spaces, the less than (assume .1%), and % sign
percent = float(row["% of Sessions"].strip().lstrip("<").strip("%"))
firmware_percents[rev] += percent
def pretty_print(d):
for k in sorted(d, key=d.get, reverse=True):
print("{0}: {1:.1f}".format(k, d[k]))
print("All versions:")
pretty_print(firmware_percents)
但是,当我这样做时,某些版本会乱序打印:
All versions:
7.0: 44.2
7.0.2: 25.7
6.1.3: 14.2
6.1.4: 5.5
7.0.1: 3.2
6.1: 2.7
# You get the point
使用这个输入文件:
Firmware Version,Sessions,% of Sessions
" iPhone 5.0.1 ",20," <0.1% "
" iPhone 6.0 ",26," 0.1% "
" iPhone 5.1.1 ",69," 0.3% "
" iPhone 5.1 ",2," <0.1% "
" iPhone 7.0 ",7401," 31.5% "
" iPhone 6.1 ",337," 1.4% "
" iPhone 6.1.3 ",2193," 9.3% "
" iPhone 6.1.2 ",84," 0.4% "
" iPhone 7.0.1 ",747," 3.2% "
" iPhone 7.0.2 ",4619," 19.7% "
" iPhone 6.0.1 ",37," 0.2% "
" iPhone 6.0.2 ",1," <0.1% "
" iPhone 6.1.4 ",1281," 5.5% "
" iPad 5.0 ",4," <0.1% "
" iPad 5.1 ",100," 0.4% "
" iPad 5.1.1 ",545," 2.3% "
" iPad 6.0 ",16," <0.1% "
" iPad 6.1 ",305," 1.3% "
" iPhone 7.0.3 ",1," <0.1% "
" iPhone 6.1.1 ",1," <0.1% "
" iPad 7.0 ",2979," 12.7% "
" iPad 6.0.1 ",100," 0.4% "
" iPad 6.1.3 ",1139," 4.9% "
" iPad 6.0.2 ",5," <0.1% "
" iPad 6.1.2 ",65," 0.3% "
" iPad 7.0.2 ",1404," 6.0% "
我试过pprint
了,虽然它确实按正确的顺序排序,但它并没有格式化浮点数(所以我最终得到了像 14.5999999996 这样的数字)。defaultdict(<class 'float'>, {'5': 3.3, '6': 24.2, '7': 73.2})
当我尝试只做主要版本时,它偶尔也会打印出奇怪的东西。
如何确保这些以格式化百分比的版本顺序打印?
按顺序我的意思是它按主要排序然后次要然后构建/超级次要(7.0.2 > 7.0.1 > 6.1.4 > 6.1 等)?