【问题标题】:Increment Object and Append to List Python增加对象并追加到列表 Python
【发布时间】:2021-08-08 02:38:10
【问题描述】:

我有一个简单的问题,但我是 Python 新手,并且在实现方面有些困难。我想输出一个对象数组,这些对象的值递增 10,以及一个特定值,它是 inflect 包的函数。这是一个示例输出:

[
    {
      "id": 1,
      "name": "one-yards",
      "shape": "rect",
      "coords": [166, 686.5, 174, 36.5],
      "opacity": 0.25,
    },
    {
      "id": 2,
      "name": "two-yards",
      "shape": "rect",
      "coords": [178, 686.5, 185, 36.5],
      "opacity": 0.25,
    }
]

请注意,在coords 中,第一个和第三个条目分别递增10 和12,而name 变量基本上是id 到文本的实现,所以我可以使用inflect 包。我想生成 10 个对象并将它们附加到列表中,这是我的代码:

import inflect as inf

converter = inf.engine()


def generate_objects(id, start_x, start_y, inc_x, inc_y):
    objects = []
    for yard in range(100):
        id += 1
        start_x += inc_x
        start_y += inc_y
        id_string = converter.number_to_words(id)
        object = "{id: " + id + ", name: "+id_string+ "-yards" + ", shape: rect, " + \
            "coords: " + [start_x, 686.5, start_y, 36.5]+", opacity:0.25}"
        objects.append(object)
        return objects


print(generate_objects(1, 166, 174, 10))

这是输出错误:

Traceback (most recent call last):
  File "number_text.py", line 18, in <module>
    print(generate_objects(1, 166, 174, 10))
  File "number_text.py", line 12, in generate_objects
    object = "{id: " + str(id) + ", name: "+id_string+", shape: rect, " + \
TypeError: can only concatenate str (not "list") to str

例如,我尝试将ints 包装在str(id) 中,但没有成功。

【问题讨论】:

  • “例如,我尝试将 int 包装在 str(id) 中,但没有成功。”在阅读TypeError: can only concatenate str (not "list") to str 之后,我不明白你为什么要尝试这个。看到括号里的not "list" 了吗?注意它是如何not "int"的?因此,问题不在于串联中有int;问题是串联中有一个list。所以,查看有问题的代码。你看到哪里有列表了吗?
  • 但是,您不应该尝试使用字符串构建技术来创建 JSON 输出。您应该使用lists 和dicts 构建结构化数据,然后使用标准库json 模块生成输出。如果您尝试过,例如,首先将python json tutorial 放入搜索引擎,您就会知道这一点。

标签: python json loops


【解决方案1】:

修复在错误代码中。 TypeError: can only concatenate str (not "list") to str

问题在于定义object的行

object = "... " + [some list] + "..."
#to fix it, you could do
object = "... " + "[some list]" + "..."

如果您尝试上述方法,您会注意到结果可能不是您想要的,因为您想要的列表将作为非可变字符串存在。

因此,您应该做的是使用您想要的相应键和值创建 dict

【讨论】:

    【解决方案2】:

    感谢您为我指明正确的方向。我已经使用了json 库并成功解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2021-01-09
      • 2021-01-10
      • 2015-05-14
      • 2013-04-16
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多