3

以下是我的计数字母编码,我需要输出为

[('e', 1), ('g', 2), ('l', 1), ('o', 2)]

我的输出是

[('e', 1), ('g', 2), ('g', 2), ('l', 1), ('o', 2), ('o', 2)]

这是我的代码

def countLetters(word):
    word=list(word)
    word.sort()
    trans=[]
    for j in word:
        row=[]
        a=word.count(j)
        row.append(j)
        row.append(a)
        trans.append(tuple(row))
    return trans

谁能解释我,如何用我的代码获得预期的输出?谢谢

4

6 回答 6

13

为什么不只使用 a Counter

例子:

from collections import Counter

c = Counter("Foobar")
print sorted(c.items())

输出:

[('F', 1), ('a', 1), ('b', 1), ('o', 2), ('r', 1)]


另一种方法是使用 adict或更好的 a defaultdict(在运行 python 2.6 或更低版本时,因为Counter是在 Python 2.7 中添加的)

例子:

from collections import defaultdict

def countLetters(word):
    d = defaultdict(lambda: 0)
    for j in word:
        d[j] += 1
    return sorted(d.items())

print countLetters("Foobar")

输出:

[('F', 1), ('a', 1), ('b', 1), ('o', 2), ('r', 1)]


或者使用简单的列表推导

word = "Foobar"
print sorted((letter, word.count(letter)) for letter in set(word))
于 2012-08-14T06:26:41.117 回答
5
>>> from collections import Counter
>>> Counter('google')
Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})
>>> from operator import itemgetter
>>> sorted(Counter('google').items(), key=itemgetter(0))
[('e', 1), ('g', 2), ('l', 1), ('o', 2)]
>>> 

实际上,没有必要key

>>> sorted(Counter('google').items())
[('e', 1), ('g', 2), ('l', 1), ('o', 2)]

由于元组首先按第一项排序,然后按第二项排序,依此类推。

于 2012-08-14T06:25:49.490 回答
2
def countLetters(word):
    k=[]
    Listing=[]
    Cororo=[]
    for warm in word:
        if warm not in k:
            k.append(warm) 
    for cold in range(len(k)):
        word.count(k[cold])
        Listing.append(word.count(k[cold]))
        Cororo.append((k[cold],Listing[cold]))
    return sorted(Cororo)

这是一种老式的做法,因为您可以像我上面的人一样使用计数器模块,让生活更轻松。

于 2016-01-02T17:36:42.760 回答
1

您可以像这样修改代码(Python 2.5+):

def countLetters(word):
    word=list(word)
    word.sort()
    trans=[]
    for j in word:
        row=[]
        a=word.count(j)
        row.append(j)
        row.append(a)
        trans.append(tuple(row))
    ans = list(set(trans))
    ans.sort()
    return ans
于 2012-08-14T06:26:15.200 回答
1

问题是您没有考虑j循环中重复出现的字母

我认为快速解决方法是将迭代修改为for j in set(word).

这确保了每个字母都被迭代一次。

于 2012-08-14T06:27:58.367 回答
-2

trans = list(set(trans))

将 a 转换list为 aset会删除重复项(我认为这是您想要做的)。

于 2012-08-14T06:26:22.217 回答