Home > database >  Converting List[str] into List[list]
Converting List[str] into List[list]

Time:01-19

I need to format the first list into the same format as the second one.

print(incorrent_format_list)
['AsKh', '2sAc', '7hQs', ...]


print(correct_format_list)
[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs'], ...]

I tried:

for h in incorrect_format_list:
         split_lines = h.split(", ")
# but the print output is this:

['AsKh']  
['2sKh']
['7hQs']


#rather than what i need: 

[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs'], ...]

CodePudding user response:

You can just slice the strings as follows:

my_list = ['AsKh', '2sAc', '7hQs']

corrected_list = [[e[:2], e[2:]] for e in my_list]

print(corrected_list)

Output:

[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]

CodePudding user response:

After learning the basic for loop method as suggested in the other answers, you could also do this in 1 line by mapping a function to each value in your initial list

a = ['AsKh', '2sAc', '7hQs']
list(map(lambda i: [i[:2], i[2:]], a))

The idea is to split each string in the middle by slicing it. 2 is being used here as each item is of a fixed length.

CodePudding user response:

Split by capital letters if that is the case in whole list

Considering incorrect_list=['AsKh', '2sAc', '7hQs']

import re
correct_format_list=[]
for i in incorrect_list:
    correct_format_list.append(re.split('(?<=.)(?=[A-Z])', i))
print (correct_format_list)

Output:

[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]

CodePudding user response:

You could use the more_itertools library and slice the string. Then append those splitted list of string into your output list (fs):

from more_itertools import sliced

ss = ['AsKh', '2sAc', '7hQs']
fs = []
for h in ss:
    fs.append(list(sliced(h, 2)))

print(fs)

Output:

[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]

  • Related