首页 > 解决方案 > 在 f 字符串中循环作为嵌入的值

问题描述

我有一个包含一些值的元组,我想将它们发送到嵌入中。他们在这样的字典里 dict = {key: [(1, 2, 3), other values here], other key: [(1, 2, 3, 4, 5), other values here]}

现在这里的一些元组长度不同,如果我使用循环添加嵌入字段,它会触发我,因为 discord 不允许 name 参数为 false 或 null。如果我使用宽度为 0 的空白字符,那么我宁愿没有很大的空间。尝试使用三元运算符,但没有奏效。我也不能这样做, for i in range(0, len(dict) - 1): pass 因为在我可以使用它来索引元组之前,循环已经结束了。我也试过做

value = f'{tuple[i] for i in range(0, len(tuple) - 1)}'

但机器人返回<generator object stats.<locals>.<genexpr> at 0x0000012E94AB3200>而不是元组内的值。

编辑:

感谢回答的人!现在可以了,谢谢

标签: pythondiscord.pyf-string

解决方案


tuple[i] for i in range(0, len(tuple) - 1)

是一个生成器表达式,它不会产生任何值,除非被循环或list()

您可以改用等效的列表理解:

f'{[tuple[i] for i in range(0, len(tuple) - 1)]}'

或者把发电机放在一个list()

f'{list(tuple[i] for i in range(0, len(tuple) - 1))}'

推荐阅读