gpt4 book ai didi

python - 如何在python中排列数据

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:09 24 4
gpt4 key购买 nike

这是这样的 data.txt 文件:

{'wood', 'iron', 'gold', 'silver'}
{'tungsten', 'iron', 'gold', 'timber'}

我想得到如下两种类型的结果:

#FIRST TYPE: sorted by item
gold: 33.3%
iron: 33.3%
silver: 16.7%
timber: 16.7%
tungsten: 16.7%

#SECOND TYPE: sorted by percentage
silver: 16.7%
timber: 16.7%
tungsten: 16.7%
gold: 33.3%
iron: 33.3%

我展示了我的代码

import collections
counter = collections.Counter()

keywords = []
with open("data.txt") as f:
for line in f:
if line.strip():
for keyword in line.split(','):
keywords.append(keyword.strip())
counter.update(keywords)

for key in counter:
print "%s: %.1f%s" %(key, (counter[key]*1.0 / len(counter))*100, '%')

但是我的结果是这样的

'silver'}: 16.7%
'iron': 33.3%
....

我想去掉结果中的大括号和撇号。

如何更改或重写以显示我想要的结果?我会等你的帮助!!

最佳答案

字典/计数器/集合是无序的。您必须先将其转换为 列表 并对列表进行排序。

例如:

for key, val in sorted(counter.items()):  #or with key=lambda x:x[0]
print "%s: %.1f%s" % (key, float(val) * 100 / len(counter), "%")

打印按键排序的值,同时:

for key, val in sorted(counter.items(), key=lambda x: (x[1], x[0])):
print "%s: %.1f%s" % (key, float(val) * 100 / len(counter), "%")

按百分比对它们排序(如果两个项目具有相同的百分比,它们也按名称排序)。

更新

关于您的解析问题,您还必须剥离 {}:

for line in f:
if line.strip():
for keyword in line.strip().strip('{}').split(','):
keyword = keyword.strip("'")

如果您使用的是最新的 python 版本(如 2.7 和/或 3),您可以改用 ast.literal_eval:

import ast
...
for line inf f:
stripped = line.strip()
if stripped:
for keyword in ast.literal_eval(stripped):

但是请注意,这将删除同一行上的重复键! (从你的例子来看,这似乎没问题......)

否则你可以这样做:

import ast
...
for line inf f:
stripped = line.strip()
if stripped:
for keyword in ast.literal_eval('[' + stripped[1:-1] + ']'):

这将保留重复项。

关于python - 如何在python中排列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com