【问题标题】:Python3 TypeError: can only concatenate list (not "str") to listPython3 TypeError:只能将列表(不是“str”)连接到列表
【发布时间】:2018-09-05 12:05:15
【问题描述】:

我正在将 odoo 11、python 2.7 移植到 python 3。我已经编辑了一个属于 odoo、python 代码的插件。

代码是:

vat = invoice.partner_id.vat or ''
vat = list(filter(lambda x: x.isnumeric(), vat[:2])) + vat[2:]

错误是:

TypeError: can only concatenate list (not "str") to list

我该如何解决这个问题,这段代码有什么问题?请帮帮我。

【问题讨论】:

  • 您能否用可能的输入更新您的问题。
  • 抱歉忘记了,我更新了。
  • 也许将 list 更改为 str 会解决
  • @Carcigenicate 但是怎么做?尝试此操作时,我遇到了同样的错误。
  • @HouLu 我试过了,没用。

标签: python python-3.x python-2.7 odoo odoo-11


【解决方案1】:
list(filter(lambda x: x.isnumeric(), vat[:2]))

上面的这个操作always返回list

vat = invoice.partner_id.vat or '' 
  • 看来,这个操作返回str(因为or '')。

如果你期望你的type(vat)==list,你应该使用

vat = invoice.partner_id.vat or []

如果您期望type(vat)==str,则应将过滤后的列表转换为str,例如

"".join(list(filter(lambda x: x.isnumeric(), vat[:2]))) + vat[2:]

【讨论】:

  • 伙计,你太棒了。你是完全正确的。非常感谢!
【解决方案2】:

使用线

vat = invoice.partner_id.vat or ''
#convert string to list
vat = [x for x in val]
vat = list(filter(lambda x: x.isnumeric(), vat[:2])) + vat[2:]

首先将字符串转换为列表。

【讨论】:

  • 我非常怀疑他们想要一个列表作为输出。 [x for x in val] 是......当您可以只使用 list(val) 时毫无意义,并且只有 vat[2:] 切片需要转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 2020-06-10
  • 2020-06-02
  • 2021-02-14
  • 1970-01-01
  • 2021-08-25
相关资源
最近更新 更多