파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)


문제 설명

파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)

Here is data.txt file like this:

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

I want to get two type of result like below:

#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%

I show my code for this result

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, '%')

However my result show like this 

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

I wan to get rid of curly brackets, apostrophe in the result.

How do I change or rewrite to show a result what I want ? I'll waiting for your help!!


참조 솔루션

방법 1:

Dictionaries/Counters/sets are not ordered. You must first convert it to a list and sort the list.

For example:

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

Prints the values sorted by key, while:

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

Sorts them by percentage(if two items have the same percentage they are sorted also by name).

Update

Regarding your parsing problem you have to strip also the { and }:

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

If you are using a recent python version(like 2.7 and/or 3) you can use ast.literal_eval instead:

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

Note however that this will remove duplicate keys on the same line! (From your example this seems okay...)

Otherwise you could do:

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

Which will preserve duplicates.

방법 2:

Use sorted to sort the items based on keys/percentage, because  dicts don't have any order.

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, '%')

output:

'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%

방법 3:

The reason for the stray { and } is that you are not getting rid of them. To do that just change your for loop to something like:

 for line in f:
     line = line.strip().strip('{}') # get rid of curly braces
     if line:
         ....

As far as printing is concerned:

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))

(by PrimingRyanBakuriuAshwini Chaudharypradyunsg)

참조 문서

  1. How arrange data in python (CC BY‑SA 3.0/4.0)

#list #Python






관련 질문

파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)

포스트백 후 모든 항목이 손실되는 CheckBoxList 컨트롤 (CheckBoxList control losing all items after post back)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

DictReader가 내 파일의 두 줄을 건너뛰고 있습니까? (DictReader is skipping two lines of my file?)

잘못된 값을 얻는 목록 확인 후 (After list checking getting wrong value)

결과를 세로 방향으로 저장하는 방법 (How do i save the result in a Vertical direction)

Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)

itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)

반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)

arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)

R 목록을 벡터로 바꾸는 방법과 목록이 필요한 이유 (R how to turn lists to vectors, and why a list at all)

python, 출력으로 코딩하는 동안 pycharm에서 이 메시지를 받았습니다. :TypeError: can't convert type 'list' to numerator/denominator (python , I got this message in pycharm while coding as output :TypeError: can't convert type 'list' to numerator/denominator)







코멘트