[英]Is there a way to use the enumerate and join functions at the same time?
I am trying to enumerate
a list of of dictionary definitions which are strings and remove the curly braces.我正在尝试
enumerate
字典定义列表,它们是字符串并删除大括号。 The definitions in the list are taken from a json (dictionary api) which is why i am using join to remove the curly brackets.列表中的定义取自 json(字典 api),这就是我使用 join 删除大括号的原因。
When I try doing them at the same time it gives a "type error: sequence item 0: expected str instance, tuple found".
当我尝试同时执行它们时,它会给出
"type error: sequence item 0: expected str instance, tuple found".
I have tried joining first and then enumerating but that comes with an error too.我试过先加入然后枚举,但这也有一个错误。
I don't believe I can use a for loop because I am assigning all 3 definitions to a single variable (to use in tkinter) and using a for loop would only show definition 3, also because I am not printing the results.我不相信我可以使用 for 循环,因为我将所有 3 个定义分配给一个变量(在 tkinter 中使用)并且使用 for 循环只会显示定义 3,也因为我没有打印结果。
Example:
definitions = [{definition1},{definition2},{definition3}]
I want to make it so that it shows:我想让它显示:
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
In Python, [{'definition1'}, {'definition2'}, {'definition3'}]
is not a list of dictionaries, it is a list of sets.在 Python 中,
[{'definition1'}, {'definition2'}, {'definition3'}]
不是字典列表,而是集合列表。
So first you need to review How to extract the member from single-member set in python?所以首先你需要回顾如何从 python 中的单成员集中提取成员? to understand how to get the members out of each set object.
了解如何从每个集合对象中获取成员。
Then you can use the enumerate built-in function to get an iterable matching up objects in the list with their position in the list, an f-string to form each line of the output, a list comprehension to collect the lines into a list, and then string.join()
to combine the lines into a single output string:然后你可以使用enumerate内置函数来获得一个可迭代的匹配列表中的对象及其在列表中的位置,一个 f-string 来形成输出的每一行,一个列表理解来将这些行收集到一个列表中,然后
string.join()
将这些行组合成一个输出字符串:
definitions = [{'definition1'},{'definition2'},{'definition3'}]
out = '\n'.join([f'{n}. {list(d)[0]}' for n, d in enumerate(definitions, start=1)]))
print(out)
Result:结果:
1. definition1
2. definition2
3. definition3
use enumerate + join can do the trick使用 enumerate + join 可以解决问题
result = ""
for idx, definition in enumerate(defintions):
result += f"{idx + 1}: {' '.join(definition.values())} \n"
if the definition is a set use如果定义是一个集合使用
result += f"{idx + 1}: {' '.join(definition)} \n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.