在python中排序

时间:2012-04-18 22:19:54

标签: python

我正在尝试学习python并擅长算法。这是我的第一语言。

例如:拿“行李”并分成“aabeggg”

string = "baggage"
count = [0] * len(string)

for x in string:
    num_value = ord(x)
    count[num_value] += 1

我认为以上是一个开始......但我真的不知道如何去做。

3 个答案:

答案 0 :(得分:4)

collections.Counter是解决这个问题的绝佳方法,但是这里有一种方法可以让你朝着前进的方向前进一步

string = "baggage"
count = [0] * 256  # This should be big enough to hold counters for every 8 bit character

for x in string:
    num_value = ord(x)
    count[num_value] += 1

for i in range(256):  # loop through all the possible 8 numbers
    if count[i]: 
        print chr(i)*count[i]

# you can join them all back into a string like this
newstr = ''.join(chr(i)*c for i,c in enumerate(count))

答案 1 :(得分:1)

我们来看看你的代码吧。

string = "baggage"
count = [0] * len(string)
# count is now [0,0,0,0,0,0,0]

for x in string:
    num_value = ord(x)
    # ord(x) gives you the ascii number value of a character x
    # So for example ord('b') = 98
    count[num_value] += 1
    # error here since count[98] isn't set.

巴勃罗给了你一个快速解决方案。我将使用可能更明确的字典写出一个。

string = "baggage"
count = {}

for c in string:
    if c in count:
        count[c] += 1
    else:
        count[c] = 1

print ''.join(count[c]*c for c in sorted(count))

答案 2 :(得分:0)

使用collections.Counter

from collections import Counter
string = 'baggage'
c = Counter(string)
result = ''.join(c[x]*x for x in sorted(c.keys()))

它的工作原理如下:

  • Counter正是您尝试使用count[num_value] += 1
  • 完成的工作
  • sorted(c.keys())为您提供排序顺序的字符
  • c[x]*x是由c[x]x''.join( ... )个副本组成的字符串
  • {{1}}将每个结果字符串连接成一个