简体   繁体   中英

Python Can I add a tuple to a generator?

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)

You want 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.

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM