【发布时间】: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放入搜索引擎,您就会知道这一点。