Python 我可以向生成器添加元组吗?
我想在前面添加 ('', 'Day') 。现在它为数字 1 到 31 创建了一个下拉菜单,我想要在顶部有一个“日”选项。
DAY_CHOICES = (
# I was hoping this would work but apparently generators don't work like this.
# ('', 'Day'),
(str(x), x) for x in range(1,32)
)
# I'll include this in the snippet in case there's some voodoo I can do here
from django import forms
class SignUpForm(forms.Form):
day = forms.ChoiceField(choices=DAY_CHOICES)
I want to add ('', 'Day') to the front. Right now it makes a drop down menu for the numbers 1 through 31 and I want a 'Day' choice at the top.
DAY_CHOICES = (
# I was hoping this would work but apparently generators don't work like this.
# ('', 'Day'),
(str(x), x) for x in range(1,32)
)
# I'll include this in the snippet in case there's some voodoo I can do here
from django import forms
class SignUpForm(forms.Form):
day = forms.ChoiceField(choices=DAY_CHOICES)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要
itertools.chain()
。You want
itertools.chain()
.这似乎是对发电机的错误使用。生成器不是列表,它是生成值序列的函数,因此不可能“将元组添加到生成器”。
模型初始化后,生成器将耗尽。例如,您可能想稍后再次使用 DAY_CHOICES —— 这是不可能的。
如果您没有任何非常具体的原因在这里使用生成器,我建议将 DAY_CHOICES 转为列表:
This seems like a bad use of generators. A generator is not a list, it is a function that generates a sequence of values, so it is not possible to "add a tuple to a generator".
The generator will be exhausted after the model initialization. You might for instance want to use DAY_CHOICES again later -- which will not be possible.
If you do not have any very specific reason for using a generator here, I would recommend turning DAY_CHOICES to a list instead: