Quiero convertir

``['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']``

a

``['60', '78', '70', '77'.. etc]``

Pensé que podría utilizar

``````for word in lines:
word = word.split(",")
newlist.append(word)
return newlist``````

pero esto produce este lugar:

``[['60', '78'], ['70', '77'], ['80', '74'], ['90', '75'], ['100', '74'], ['110', '75']]``

Puede alguien por favor ofrecer una solución?

InformationsquelleAutor GBA13 | 2015-01-11

#### 3 Comentarios

1. Necesita utilizar `lista.ampliar` en lugar de `list.append`.

``````newlist = []
for word in lines:
word = word.split(",")
newlist.extend(word)  # <----
return newlist``````

O, utilizando lista de comprensión:

``````>>> lst = ['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
>>> [x for xs in lst for x in xs.split(',')]
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']``````
2. `str.split` en realidad devuelve una lista.

Ya que está anexando la lista devuelta a `newlist`, vas a encontrar una lista de listas. En lugar de utilizar `list.extend` método, como este

``````for word in lines:
newlist.extend(word.split(","))``````

Pero simplemente puede usar la lista anidada de la comprensión como este

``````>>> data = ['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
>>> [item for items in data for item in items.split(",")]
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']``````
3. utilizando itertools.la cadena de :

``````from itertools import chain

print(list(chain.from_iterable(ele.split(",") for ele in l)))
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']``````

Los elementos más tienes que aplanar la cadena hace un poco más eficaz:

``````In [1]: l= ["1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20" for _ in range(100000)]

In [2]: from itertools import chain

In [3]: l= ["1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30" for _ in range(10000)]

In [4]: timeit (list(chain.from_iterable(ele.split(",") for ele in l)))
100 loops, best of 3: 17.7 ms per loop

In [5]: timeit  [item for items in l for item in items.split(",")]
10 loops, best of 3: 20.9 ms per loop``````