Home > Mobile >  Python find maximum string length in the list of lists of lists
Python find maximum string length in the list of lists of lists

Time:12-09

big_list = [[['asdf','ad'],['aqwe','rt']],['lkjyui','op'],['dfgh','hjk']]

Goal is to find the maximum string length in the whole big_list

My approach:

big_list = [[['asdf','ad'],['aqwe','rt']],['lkjyui','op'],['dfgh','hjk']]

listdf= pd.concat(pd.DataFrame(item).T for item in big_list ).reset_index(drop=True)
listdf = 
       0     1
0    asdf  aqwe
1      ad      
2  lkjyui    op
3    dfgh   hjk

print(listdf.astype(str).applymap(lambda x: len(x)).max().max())
6

Is there a better way of doing it?

CodePudding user response:

With pandas:

out = listdf.stack().str.len().max()

In pure python:

out = max(len(x) for l in big_list for x in l)

Output: 6

CodePudding user response:

If uisng pandas then

one = list(pandas.core.common.flatten(big_list))
print(len(max(one, key=len)))

give #

6
  • Related