Reputation: 415
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]
Upvotes: 5
Views: 439
Reputation: 784
This works as well:
test = [[row[0].split('.')[0], row[0].split('.')[1], row[1], row[2]] for row in test]
Upvotes: 3
Reputation: 2214
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]
Upvotes: 6
Reputation: 14273
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]]
Upvotes: 3
Reputation: 312404
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]
Upvotes: 5