How can I split the first element of a nested list element?

Viewed 219

Let's imagine we have:

test = [['word.II', 123, 234],
    ['word.IV', 321, 123],
    ['word.XX', 345, 345],
    ['word.XIV', 345, 432]
   ]

How can I split the first element in the test so that the result would be:

test = [['word', 'II', 123, 234],
    ['word', 'IV', 321, 123],
    ['word', 'XX', 345, 345],
    ['word', 'XIV', 345, 432]
   ]  

Among other things I've tried:

test = [[row[0].split('.'), row[1], row[2]] for row in test], 

but that results in:

[['word', 'II'], 123, 234]
[['word', 'IV'], 321, 123]
[['word', 'XX'], 345, 345]
[['word', 'XIV'], 345, 432] 
5 Answers

This is one way to do that:

new_test = [row[0].split('.')+ row[1:] for row in test]

+ operator concatenates lists, for example:

>>>[2,3,4] + [1,5]
[2, 3, 4, 1, 5]

One approach could be to use split to split the first element (as you did!) and then concatenate it to the rest of the list using the + operator:

result = [row[0].split('.') + row[1::] for row in test]

Try this solution:

list(map(lambda x:x[0].split('.')+x[1:],test))

using extended iterable unpacking and list addition:

spam = [['word.II', 123, 234],
    ['word.IV', 321, 123],
    ['word.XX', 345, 345],
    ['word.XIV', 345, 432]]


eggs = [first.split('.') + rest for first, *rest in spam]
print(eggs)

output:

[['word', 'II', 123, 234], ['word', 'IV', 321, 123],
 ['word', 'XX', 345, 345], ['word', 'XIV', 345, 432]]

This works as well:

test = [[row[0].split('.')[0], row[0].split('.')[1], row[1], row[2]] for row in test]
Related