首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中排列数据

如何在python中排列数据
EN

Stack Overflow用户
提问于 2013-05-11 14:56:28
回答 3查看 377关注 0票数 1

下面是如下所示的data.txt文件:

代码语言:javascript
复制
{'wood', 'iron', 'gold', 'silver'}
{'tungsten', 'iron', 'gold', 'timber'}

我希望得到两种类型的结果,如下所示:

代码语言:javascript
复制
#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%

我展示了这个结果的代码

代码语言:javascript
复制
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, '%')

然而,我的结果如下所示

代码语言:javascript
复制
'silver'}: 16.7%
'iron': 33.3%
....

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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-05-11 15:12:02

使用sorted根据键/百分比对项进行排序,因为字典没有任何顺序。

代码语言:javascript
复制
from collections import Counter
counter = Counter()
import ast
keywords = []
with open("abc") as f:
    for line in f:
        #strip {} and split the line at ", " 
        line = line.strip("{}\n").split(", ")
        counter += Counter(x.strip('"') for x in line)

le = len(counter)    
for key,val in sorted(counter.items()):
    print "%s: %.1f%s" %(key, (val*1.0 / le)*100, '%')

print

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

输出:

代码语言:javascript
复制
'gold': 33.3%
'iron': 33.3%
'silver': 16.7%
'timber': 16.7%
'tungsten': 16.7%
'wood': 16.7%

'silver': 16.7%
'timber': 16.7%
'tungsten': 16.7%
'wood': 16.7%
'gold': 33.3%
'iron': 33.3%
票数 1
EN

Stack Overflow用户

发布于 2013-05-11 15:09:22

未订购Dictionaries/Counters/sets。您必须首先将其转换为list并对列表进行排序。

例如:

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

打印按键排序的值,而:

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

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

更新

关于您的解析问题,您还必须对{}进行strip

代码语言:javascript
复制
for line in f:
    if line.strip():
        for keyword in line.strip().strip('{}').split(','):
            keyword = keyword.strip("'")

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

代码语言:javascript
复制
import ast
...
for line inf f:
    stripped = line.strip()
    if stripped:
        for keyword in ast.literal_eval(stripped):

但是请注意,这将删除同一行上的重复键!(从您的示例来看,这似乎还可以...)

否则,您可以这样做:

代码语言:javascript
复制
import ast
...
for line inf f:
    stripped = line.strip()
    if stripped:
        for keyword in ast.literal_eval('[' + stripped[1:-1] + ']'):

这样就可以保存副本了。

票数 2
EN

Stack Overflow用户

发布于 2013-05-11 15:26:11

出现杂乱的{}的原因是您没有摆脱它们。

要做到这一点,只需将for循环改为如下所示:

代码语言:javascript
复制
 for line in f:
     line = line.strip().strip('{}') # get rid of curly braces
     if line:
         ....

就打印而言:

代码语言:javascript
复制
print "Sorted by Percentage"
for k,v in sorted(c.items(), key=lambda x: x[1]):
    print '{0}: {1:.2%}'.format(k, float(v)/len(c))
print 
print "Sorted by Name"
for k,v in  sorted(c.items(), key=lambda x :x[0]):
    print '{0}: {1:.2%}'.format(k, float(v)/len(c))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16494634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档