简体   繁体   中英

How to apply a function to an element at a particular position in every tuple inside a tuple of tuples?

I have this tuple of tuples;

Tuple = ( ('AA', 'BB', datetime.datetime(2014, 3, 2, 0, 0) ), ('CC', 'DD', datetime.datetime(2014, 3, 2, 0, 1) )  )

I want to convert it to look like this;

Output= ( ('AA', 'BB', '2014-3-2 00:00:00' ), ('CC', 'DD', '2014-3-2 00:00:00'  )

The 3rd element of each tuple is to be converted into a string representing the datetime. This can be done with something like this Tuple[0][2].strftime('%Y-%m-%d %H:%M:%S')

The problem which I am stuck at is how do I apply this function strftime() to the 3rd element of every tuple inside this tuple of tuples?

You'll have to generate the tuples again. You can do so with the following list comprehension.

>>> [(a, b, date.strftime('%Y-%m-%d %H:%M:%S')) for (a, b, date) in Tuple]
[('AA', 'BB', '2014-03-02 00:00:00'), ('CC', 'DD', '2014-03-02 00:01:00')]

If the end result needs to be a tuple, use tuple() . This one uses a generator expression, but basically works the same:

>>> tuple((a, b, date.strftime('%Y-%m-%d %H:%M:%S')) for (a, b, date) in Tuple)
(('AA', 'BB', '2014-03-02 00:00:00'), ('CC', 'DD', '2014-03-02 00:01:00'))

List comprehension as @msvalkon mentioned, or using map and lambda :

In [731]: map(lambda tup: (tup[0], tup[1], tup[2].strftime('%Y-%m-%d %H:%M:%S')), Tuple)
Out[731]: [('AA', 'BB', '2014-03-02 00:00:00'), ('CC', 'DD', '2014-03-02 00:01:00')]

Here's a generator function that does the trick.

import datetime

def convert_nested(nested_tuples):
    for a, b, time in nested_tuples:
        yield (a, b, time.strftime('%Y-%m-%d %H:%M:%S'))

if __name__ == '__main__':
    nested_tuples = (('AA', 'BB', datetime.datetime(2014, 3, 2, 0, 0)),
                     ('CC', 'DD', datetime.datetime(2014, 3, 2, 0, 1)))

    output = tuple(convert_nested(nested_tuples))

    print(output)

Or more concisely as a generator comprehension.

import datetime

if __name__ == '__main__':
    nested_tuples = (('AA', 'BB', datetime.datetime(2014, 3, 2, 0, 0)),
                     ('CC', 'DD', datetime.datetime(2014, 3, 2, 0, 1)))

    output = tuple((a, b, time.strftime('%Y-%m-%d %H:%M:%S')) 
                   for a, b, time in nested_tuples)

    print(output)

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