如何将字符串从大到小、按字母顺序整理出结果?[重复]

问题描述 投票:0回答:2
def word_count(str):
    counts = dict()
    words = str.split()

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1

    return counts


print(word_count("""the quick brown fox jumps over the lazy lazy lazy dog."""))

输出。

{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 3, 'dog.': 1}

但我想有两个输出,一个是这样的

{3 : 'lazy',2 :'the',1 : 'quick',1 : 'brown',1 : 'fox',1 : 'jumps',1 : 'over',1 : 'dog'}

另一个像这样按字母顺序排列。

 ['brown' : 1,'dog.' : 1,'fox' : 1,'jumps' 1: ,'lazy' 3: , 'over': 1,'quick' 1: ,'the' : 2]

我知道用sorted可以按字母顺序排列 但我不知道如何把它和结果放在一起. 我找遍了Stack-overflow和其他地方,看是否能找到任何结果,但我找不到任何东西。

python resultset helper
2个回答
0
投票

你可以用以下的结果来做类似的事情 word_count

res = word_count("""the quick brown fox jumps over the lazy lazy lazy dog.""")
word_list = list(res.items())
inverted_list = [t[::-1] for t in word_list]

by_word = sorted(word_list, key=lambda t: t[0], reverse = True) 
by_count = sorted(inverted_list, key=lambda t: t[0], reverse = True) 

print(by_word)
print(by_count)

请记住,你所期望的输出是不可能的。取而代之的是,这给你提供了一个数组,其值按照你的要求进行了排序。


0
投票

正如其他人所说,你想要的结果是没有意义的,因为它们是无效的。然而,如果你想要一个与你提供的最终示例相匹配的排序集合,你可以使用类似下面的东西。

data = """the quick brown fox jumps over the lazy lazy lazy dog."""

def word_count(str):
    result = {}
    words = str.split()
    for word in words:
      if word not in result:
        result[word] = words.count(word)
    return dict(sorted(result.items()))

print(word_count(data))

这将产生...

{'brown': 1, 'dog.': 1, 'fox': 1, 'jumps': 1, 'lazy': 3, 'over': 1, 'quick': 1, 'the': 2}
© www.soinside.com 2019 - 2024. All rights reserved.