【问题标题】:Loop inside an f-string as a value for an embed在 f 字符串中循环作为嵌入的值
【发布时间】:2021-02-22 04:18:24
【问题描述】:

我有一个包含一些值的元组,我想将它们发送到嵌入中。他们在这样的字典里 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> 而不是元组内的值。

编辑:

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

【问题讨论】:

  • 将语句放入[]:f'{[my_tuple[i] for i in range(0, len(my_tuple) - 1)]}',也可能不想将变量命名为tuple

标签: python discord.py f-string


【解决方案1】:
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))}'

【讨论】:

    【解决方案2】:

    因为你的理解没有包含在 [] 中,所以它在技术上是一个生成器表达式 ()(我认为这在 python 2.7 中可以工作),试试这个:

    my_tuple = (1, 2, 3, 4)
    
    f'{[my_tuple[i] for i in range(0, len(my_tuple) - 1)]}'
    

    输出:

    [1, 2, 3]
    

    另外,python 中没有元组推导,因为元组是不可变的。

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 2020-01-29
      • 2022-01-26
      • 2017-05-04
      • 2019-07-11
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多