Split string value in array of arrays in Python

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

What I have:

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

What I would like:

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

How can I do this conversion? This is always the second value and always has two numbers. I know what I should use .split('-'), but I know that I don’t know, to make it work here, to make a replacement, since I have to repeat all the arrays included in arr.

Thanks in advance.

+4
source share
5 answers

If you want to do this in place:

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']]
+12
source

try it

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
+2

:

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

? , , . ,

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

. 1:2 ( 1 , 2), - .

, , . . , - ...

EDIT: Onliner , :

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

? ... , , __setslice__ . or a arr, __setslice__ None.

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

Without changing the source array (with copy):

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

On-site solution:

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

Source: https://habr.com/ru/post/1529178/


All Articles