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

发布于 2024-12-14 04:31:09 字数 432 浏览 0 评论 0原文

我想在前面添加 ('', '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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南城追梦 2024-12-21 04:31:09

您需要 itertools.chain()

for i in itertools.chain(('foo', 'bar'), xrange(1, 4)):
  print i

You want itertools.chain().

for i in itertools.chain(('foo', 'bar'), xrange(1, 4)):
  print i
安稳善良 2024-12-21 04:31:09

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

模型初始化后,生成器将耗尽。例如,您可能想稍后再次使用 DAY_CHOICES —— 这是不可能的。

如果您没有任何非常具体的原因在这里使用生成器,我建议将 DAY_CHOICES 转为列表:

DAY_CHOICES = [('', 'Day')] + [(str(x), x) for x in range(1,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.

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')] + [(str(x), x) for x in range(1,32)]
债姬 2024-12-21 04:31:09
DAY_CHOICES = ( (str(x),x) if x>0 else('','Day') for x in range(0,32) )
DAY_CHOICES = ( (str(x),x) if x>0 else('','Day') for x in range(0,32) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文