[英]Python Can I add a tuple to a generator?
I want to add ('', 'Day') to the front. 我想在前面添加('','Day')。 Right now it makes a drop down menu for the numbers 1 through 31 and I want a 'Day' choice at the top. 现在,它为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)
You want itertools.chain()
. 您需要itertools.chain()
。
for i in itertools.chain(('foo', 'bar'), xrange(1, 4)):
print i
DAY_CHOICES = ( (str(x),x) if x>0 else('','Day') for x in range(0,32) )
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. 例如,您可能想稍后再使用DAY_CHOICES-这将是不可能的。
If you do not have any very specific reason for using a generator here, I would recommend turning DAY_CHOICES to a list instead: 如果您在此处没有使用生成器的特定原因,建议您将DAY_CHOICES改为列表:
DAY_CHOICES = [('', 'Day')] + [(str(x), x) for x in range(1,32)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.