【问题标题】:Not able to write an return of a function to file无法将函数的返回写入文件
【发布时间】:2015-12-16 17:37:52
【问题描述】:

谁能解释一下为什么我不能这样做以及是否有任何解决方法?

这适用于前。

a, b, c, d = extract(text)

fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(a, b, c, d))

但这不是

fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(extract(text)))

【问题讨论】:

  • extract 函数是什么?
  • ... .format(extract(text))) 更改为 ... .format(*extract(text)))

标签: python file-io io format


【解决方案1】:

如果extract()返回一个元组,则需要先解包返回值,然后再将其传递给format:

.format(*extract(text))

星号在这里起到了作用。

解释:在 Python 中,string#format 具有以下签名:

.format(*args, **keyword_args)

*** 被称为解包运算符(在 Ruby 中,它们被称为 splats)。它们的唯一目的是将列表(元组、数组)和字典(字典、对象)分别转换为参数列表。

extract() 返回一个列表,但格式需要一个参数列表。所以之前,你有:

#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar']
.format(extract(text)) # this thing
.format(('foo', 'bar')) # is equivalent to this, note the parentheses

在这种情况下,元组('foo','bar')等于第一个格式标记{0},格式不知道如何处理一个元组标记(元组的哪些元素我应该使用吗?)。

当您使用扩展运算符时,您将extract() 的输出转换为函数所期望的列表,因此:

#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar']
.format(*extract(text)) # this thing
.format('foo', 'bar') # is equivalent to this

【讨论】:

  • 你说得对,反正我忘了说我要返回 4 个参数。如果你能解释一下这意味着什么
猜你喜欢
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 2019-12-04
  • 2018-07-15
  • 1970-01-01
  • 2016-09-02
相关资源
最近更新 更多