1

I have a list of tuples:

Months = [('2011-01-01', '2011-02-01'), ('2011-02-01', '2011-03-01'), ('2011-03-01', '2011-04-01'), ...]

I would like to define a function that loops through the list, and calls the elements of the tuple independently. For example:

def function(list):
    print """
    Start %s
    End %s
    """ % list

I would them do something like:

for tuple in months:
    function(tuple)

Obviously I have a problem as I have two %s's but only one argument.

Is there a way to do this?

4

2 回答 2

1

Just make lst a tuple, so call function for each element in your Months list:

for start_end in Months:
    func(start_end)

and make your string use three quotes:

def func(tup):
    print """
    Start %s
    End %s
    """ % tup

String formatting supports passing in a tuple defined in a variable, as long as it has the correct length:

>>> tup = ('2011-01-01', '2011-02-01')
>>> print """
...     Start %s
...     End %s
...     """ % tup

    Start 2011-01-01
    End 2011-02-01

Alternatively, use str.format() to format:

def func(tup):
    print """
    Start {0[0]}
    End {0[0]}
    """.format(tup)

You can also use tuple unpacking; assign each tuple in the list to two variables in the loop:

for start, end in Months:
    print 'Start {}\nEnd'.format(start, end)
于 2013-07-26T23:12:40.903 回答
1
for date1, date2 in Months:
    print """"
    Start %s
    End %s
    """" % (date1, date2)
于 2013-07-26T23:12:56.020 回答