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]
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With