Home > Back-end >  Convert items of a list of lists with different format conversion
Convert items of a list of lists with different format conversion

Time:08-04

I have the following list of lists (denoted by lol):

[['365', '336', '365', 'E<;EjD'],
 ['365', '336', '365', 'E<;EkD'],
 ['365', '336', '365', 'E<;F0D'],
 ['0', '0', '335', 'E<;GaQ'],
 ['0', '0', '335', 'E<;GbQ']]

I am trying to convert lol in such a way that each first three strings of a sub-list to be converted to int and each last string of the same sub-list to be converted to datetime (dateConverter() is to convert string to daytime).

I am expecting to have as output the following:

[[365, 336, 365, '2021-12-11T21:58:20'],
 [365, 336, 365, '2021-12-11T21:58:20'],
 [365, 336, 365,  '2021-12-11T21:59:20'],
 [0, 0, 335, '2021-12-11T22:0:20'],
 [0, 0, 335, '2021-12-11T22:1:20']]

I tried the following:

  1. I knew how to convert the first three strings to int.
[list(map(int, li[:-1])) for li in lol]
  1. I knew how to convert the last string to daytime.
list(map(dateConverter, [li[-1] for li in lol]))
  1. I did not know how to do that 2-in-1 using map function or any other way. I tried the following but did not work for me.
[list(map(int, dateConverter, li[:-1], li[-1])) for li in lol]

CodePudding user response:

What about this?

lol = [['365', '336', '365', 'E<;EjD'],
    ['365', '336', '365', 'E<;EkD'],
    ['365', '336', '365', 'E<;F0D'],
    ['0', '0', '335', 'E<;GaQ'],
    ['0', '0', '335', 'E<;GbQ']]
    
converted = [
    [int(x) if i < 3 else date_converter(x) for (i, x) in enumerate(li)] for li in lol
]

CodePudding user response:

You can try this:

[int(t[0]),int(t[1]),int(t[2]),dateConverter(t[3]) for t in lol]

CodePudding user response:

Another option, using a custom lambda:

convert = lambda record: list(map(int, [record[:3]]))   [dateConverter(record[4])]
result = map(convert, lol)
  • Related