【问题标题】:Dictionary manipulation in PythonPython中的字典操作
【发布时间】:2012-02-20 20:32:18
【问题描述】:

我有一段文字,我在 python 中创建了一个字典。它将单词作为键,单词在文本中出现的次数作为值。该字典按值字段的递减值排序。这是我列表中的一个 sn-p:

[('the\n', 1644), ('and\n', 872), ('to\n', 729), ('a\n', 632), ('she\n', 541), 
('it\n', 530), ('of\n', 514), ('said\n', 462), ('i\n', 410), ('alice\n', 386),
('in\n', 369), ('you\n', 365), ('was\n', 357), ('that\n', 280), ('as\n', 263), 
('her\n', 248), ('at\n', 212), ('on\n', 193), ('all\n', 182), ('with\n', 181),
('had\n', 178), ('but\n', 170), ('for\n', 153), ('so\n', 151), ('be\n', 148), 
('not\n', 145), ('very\n', 144), ('what\n', 136), ('this\n', 134),
('they\n', 130), ('little\n', 128), ('he\n', 120), ('out\n', 117),
('is\n', 108), ... ]

我想打印 25 个最常用的单词。这相当简单,我已经做到了。下一部分是打印以字母“f”开头的 25 个最常用的单词。如何找到这个并将其附加到 25 个最常用词的列表中?

另外,我必须添加所有单词的排名。例如,在我的字典中,“the”将排在第 1 位,“and”排在 2 位,依此类推。如何在单词列表中添加排名?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    一种选择是使用itertools.ifilter()itertools.islice()

    f_words = islice(ifilter(lambda x: x[0].startswith("f"), words), 25)
    for word, count in f_words:
        print word.rstrip()
    

    除了ifilter(),您还可以使用生成器表达式:

    f_words = islice((w for w, c in words if w.startswith("f")), 25)
    for word in f_words:
        print word.rstrip()
    

    这两种方法的优点是您不需要先过滤整个列表 - 循环将在 25 个单词后停止。

    【讨论】:

      【解决方案2】:

      只需使用列表推导进行过滤:

      f_words = [(word, freq) for (word, freq) in the_list if word.startswith('f')]
      

      由于原始列表已排序,因此此列表也将排序。然后,您可以将其切片以获得前 25 名:f_words[:25]

      【讨论】:

      • 如果我想从 1-25 开始对这些文档进行排名,如何将排名包含在键值对列表中?
      • 您可以使用enumerate(some_list, 1) 来获取(索引,元素)对。 1 表示起点,否则从零开始计数。
      猜你喜欢
      • 2018-08-11
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多