Avión
Avión

Reputation: 8396

Split value of string within array of arrays in Python

I've an arrays of arrays called arr and I want to split the second value of each array. This means, if I've 0-6 I would like to modify it to '0','6'

What I have:

arr = [['PROVEEDOR', '0-6', '11111'], ['tiempo ida pulidor', '6-14', '33333']]

What I would like to have:

arr = [['PROVEEDOR', '0', '6', '11111'], ['tiempo ida pulidor', '6', '14', '33333']]

How can I do this conversion? It's always the second value, and always have two numbers. I know I've to use .split('-') but I know dont know to make it work here to make the replacement, as I've to iterate between all the arrays included in arr.

Thanks in advance.

Upvotes: 4

Views: 1363

Answers (5)

m.wasowski
m.wasowski

Reputation: 6387

Without changing original array (with copy):

result = [[ar[0]] + ar[1].split('-') + ar[2:] for ar in arr]

In-place solution:

for ar in arr:
    x,y = ar[1].split('-')
    ar[1] = x
    ar.insert(2, y)

Upvotes: 0

Daren Thomas
Daren Thomas

Reputation: 70324

Try this:

def splitfirst(a):
    a[1:2] = a[1].split('-')
    return a
newarr = [splitfirst(a) for a in arr]

What is going on? Well, you can assign to a slice, replacing that portion of the list with a new sequence. That is what the line

a[1:2] = [1, 2, 3, ...]

does. It replaces the slice 1:2 (element with index 1 up to but not including element with index 2) with the new sequence - the result of our splitting in this case.

Since this solution relies on assigning to a slice, which is a statement, we can't do this without a separate function. Wait. I'm going to go and see if I can find something...

EDIT: Onliner for those who like that:

[a.__setslice__(1, 2, a[1].split('-')) or a for a in arr]

What is going on here? Well... actually exactly the same as before, but using the magic method __setslice__ instead of the syntactic sugar of slice assignment. I use the or a part of the expression to produce the arr element, since __setslice__ returns None.

Upvotes: 2

lima
lima

Reputation: 361

for a in arr:
   elems = a.pop(1).split('-')
   a.insert(1, elems[0])
   a.insert(2, elems[1])

Upvotes: 1

Neel
Neel

Reputation: 21285

try this

arr = [['PROVEEDOR', '0-6', '11111'], ['tiempo ida pulidor', '6-14', '33333']]

new_arr = []
for x in arr:
    new_val = [x[0]]
    new_val.extend(x[1].split('-'))
    new_val.append(x[2])
    new_arr.append(new_val)

print new_arr

Upvotes: 2

zhangxaochen
zhangxaochen

Reputation: 34027

If you want to do it inplace:

In [83]: arr = [['PROVEEDOR', '0-6', '11111'], ['tiempo ida pulidor', '6-14', '33333']]

In [84]: for i in arr:
    ...:     i[1:2]=i[1].split('-')

In [85]: arr
Out[85]: [['PROVEEDOR', '0', '6', '11111'], ['tiempo ida pulidor', '6', '14', '33333']]

Upvotes: 12

Related Questions