Skip to content
Advertisement

Convert items of a list of lists with different format conversion

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]

Advertisement

Answer

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
]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement