是否有一种方法可以同时使用枚举和连接函数?



我试图enumerate一个列表的字典定义是字符串,并删除花括号。列表中的定义取自json(字典api),这就是为什么我使用join来删除大括号。

当我尝试同时做它们时,它给出了一个"type error: sequence item 0: expected str instance, tuple found".,我尝试先加入,然后枚举,但这也有一个错误。

我不相信我可以使用for循环,因为我将所有3个定义分配给一个变量(在tkinter中使用),并且使用for循环只会显示定义3,也因为我没有打印结果。

Example:
definitions = [{definition1},{definition2},{definition3}]

我想让它显示:

result =  1. definition1
2. definition2
3. definition3
I have achieved the same result by doing:
result = "1. " + definitions[0] + "n" + "2. " + definitions[1] + "n" + "3. " + definitions[2]
but would rather be able to do it in a way that doesn't require me to type out everything manually

在Python中,[{'definition1'}, {'definition2'}, {'definition3'}]不是一个字典列表,而是一个集合列表。

所以首先你需要复习如何在python中从单成员集合中提取成员?了解如何从每个set对象中获取成员。

然后可以使用enumerate内置函数获得一个可迭代对象,将列表中的对象与其在列表中的位置匹配起来,一个f字符串形成输出的每一行,一个列表推导将这些行集合成一个列表,然后string.join()将这些行组合成一个单独的输出字符串:

definitions = [{'definition1'},{'definition2'},{'definition3'}]
out = 'n'.join([f'{n}. {list(d)[0]}' for n, d in enumerate(definitions, start=1)]))
print(out)

结果:

1. definition1
2. definition2
3. definition3

使用enumerate + join可以达到目的


result = ""
for idx, definition in enumerate(defintions):
result += f"{idx + 1}: {' '.join(definition.values())} n"

如果定义是一个集合,则使用

result += f"{idx + 1}: {' '.join(definition)} n"

最新更新