Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] 
like image 313
LeLuc Avatar asked Jan 16 '21 17:01

LeLuc


People also ask

How do you extract an element from a nested list in Python?

Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.

How do you pop an element in a nested list?

Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.

How do you split a specific item in a list Python?

To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.


3 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]
like image 104
Tugay Avatar answered Sep 22 '22 13:09

Tugay


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]
like image 30
Mureinik Avatar answered Sep 23 '22 13:09

Mureinik


Try this solution:

list(map(lambda x:x[0].split('.')+x[1:],test))
like image 37
Walid Avatar answered Sep 25 '22 13:09

Walid