【问题标题】:python function calling with dict - calling a function which has parameters but not listing the parameter explicitly使用 dict 调用 python 函数 - 调用具有参数但未显式列出参数的函数
【发布时间】:2018-09-23 07:37:27
【问题描述】:

我有一个脚本,用于计算名为 alice 的文本文件中的单词数。从https://developers.google.com/edu/python/dict-files 开始练习,我了解它是如何工作的,但此处显示的一个例外是:

def get_count(word_count_tuple):
  return word_count_tuple[1]

我的理解是这个函数在物品被排序时被调用并且它们是按照'get_count'的值排序的 'get_count' 有参数'word_count_tuple',在任何阶段都没有使用/分配,并且返回'word_count_tuple1'。 有人可以解释这里发生了什么,以及它是如何工作的,因为我认为函数必须传递一个参数值,或者有一个默认值,而这没有。还是它以某种方式与密钥一起分配而我错过了它?

这是完整的代码:

def word_count_dict(filename):
  word_count = {}
  input_file = open(filename, "r")
  for line in input_file:
    words = line.split()
    for word in words:
      word = word.lower()
      if not word in word_count:
        word_count[word] = 1
      else:
        word_count[word] += 1
  input_file.close()
  return(word_count)

def get_count(word_count_tuple):
  return word_count_tuple[1]

def print_top(filename):
  word_count = word_count_dict(filename)
  items = sorted(word_count.items(), key = get_count, reverse = True)
  for item in items[:20]:
    print (item[0], item[1])

def main():
  filename = "alice.txt"
  print_top(filename)

if __name__ == '__main__':
  main()

【问题讨论】:

    标签: python python-3.7


    【解决方案1】:

    你是部分正确的,你需要传递一个参数。 看看这一行

    items = sorted(word_count.items(), key=get_count, reverse=True)
    

    在这一行中,您将根据计数而不是单词返回 word_count 的排序(按非递增顺序)副本。

    看看key。它需要一个函数,该函数返回一个值,我们需要根据该值对我们正在排序的列表中的每个元素进行排序。

    意思是如果word_count.items() 中的每个元素都是x,那么我们必须使用x[1] 对列表进行排序,x[1] 是值,x[0] 是键。

    key 将函数或 lambda 对象作为其值,该值“应用于”要排序的列表中的每个项目。

    实现相同功能的另一种方法是

    items = sorted(word_count.items(), key=lambda x: -x[1])
    

    这会按值的负数对项目进行排序,这样我们就可以得到反向排序的列表!

    【讨论】:

    • 密钥遍历 word_count 字典中的每一个“事物”。 word_count 有两个赋值,单词 x[0] 和单词 x[1] 的值/出现次数。当它被排序时,它会循环通过键(即单词)排序的所有内容,但是当它被拆分为项目(单词 x[0],值 x[1])时 word_count_tuple[1] 的返回返回计数?那是对的吗?如果是这样我明白了
    • 快速跟进问题,为什么你不能只做 key = word_count[1]?我试过了,它出现了一个错误,但它的原因是什么?我不明白
    • word_count 是你正在排序的字典,word_count[1] 只对返回对应于键 1 的值有意义,这没有意义吧?
    • key 所做的是 -> 对于container 中的每个x,将xkey(x) 排序
    • 这不是函数所做的吗?最终结果不一样吗?
    【解决方案2】:

    是的,当您第一次看到它时,这有点令人困惑。

    get_countsorted() 函数调用,并从word_count.items() 逐个传递项目。

    如果您的字数统计词典如下所示:

    {'mark': 2, 'the': 5, 'hotdog': 1}
    

    那么items() 将是一个迭代器,其值如下:

    [('mark', 2), ('the', 5), ('hotdog', 1)]
    

    So sorted 获取其中的每一个并将其传递给get_count,例如get_count(('mark', 2))get_count,然后返回2sorted 将其用作排序键。

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      相关资源
      最近更新 更多