retr0327
retr0327

Reputation: 187

How to split items in Python list?

How can I turn the following list:

[['110T148A112', '24,0001100409'], 
 ['110T148A077','24,0001100316']]

into

[['110T148A112', '24,000', '1100409'], 
 ['110T148A077','24,000', '1100316']]

What is the syntactically cleanest way to accomplish this?

Thanks for any help!!

Upvotes: 0

Views: 152

Answers (2)

Ajax1234
Ajax1234

Reputation: 71471

You can use re.findall to handle greater variability in the positioning and number of commas present in the strings:

import re
d = [['110T148A112', '24,0001100409'], ['110T148A077', '24,0001100316']]
r = [[a, *re.findall('(?<=,\d{3})\d+$|^\d+(?:,\d{3})+', b)] for a, b in d]

Output:

[['110T148A112', '24,000', '1100409'], ['110T148A077', '24,000', '1100316']]

Upvotes: 2

Nick
Nick

Reputation: 147216

If all the data is in the same format, you could just use a list comprehension with string slices:

lst = [['110T148A112', '24,0001100409'], 
 ['110T148A077','24,0001100316']]


res = [[l[0], l[1][:6], l[1][6:]] for l in lst]

Output:

[
 ['110T148A112', '24,000', '1100409'],
 ['110T148A077', '24,000', '1100316']
]

Upvotes: 1

Related Questions