Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python我可以向生成器添加元组吗?_Python_Django_Forms_Tuples_Generator - Fatal编程技术网

Python我可以向生成器添加元组吗?

Python我可以向生成器添加元组吗?,python,django,forms,tuples,generator,Python,Django,Forms,Tuples,Generator,我想在前面加上('',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 cas

我想在前面加上('',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)
你想要的


这似乎是对发电机的不当使用。生成器不是列表,它是一个生成值序列的函数,因此不可能“向生成器添加元组”

模型初始化后,发电机将耗尽。例如,您可能希望稍后再次使用DAY_选项——这是不可能的

如果您没有任何非常具体的理由在此处使用生成器,我建议您将DAY_选项改为列表:

DAY_CHOICES = [('', 'Day')] + [(str(x), x) for x in range(1,32)]

目标不是打印它,而是将其作为参数传递给构造函数。如果开发人员对原始iterable拥有绝对控制权,则是。似乎更适合使用它。在一般情况下,当然可以。但在这种特殊情况下,你永远不会重复使用发电机。你是对的。但最好将其设置为一个元组,因为它的值可能不会改变:
DAY_CHOICES=('',DAY'),+tuple((str(x),x)表示范围(1,32)内的x)
DAY_CHOICES=tuple((str(x),x)如果x>0,则范围(0,32)内的x('','DAY')
我根据你的建议将其更改为一个元组。
DAY_CHOICES = ( (str(x),x) if x>0 else('','Day') for x in range(0,32) )
DAY_CHOICES = [('', 'Day')] + [(str(x), x) for x in range(1,32)]