¿Cómo convertir una cadena delimitada por comas a una lista en Python?
Dada una cadena que es una secuencia de varios valores separados por una commma:
mStr = 'A,B,C,D,E'
¿Cómo convertir la cadena a una lista?
mList = ['A', 'B', 'C', 'D', 'E']
104
Author: FreeAsInGimme, 2011-10-21
3 answers
Puede usar el str.método split.
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']
Si desea convertirlo en una tupla, solo
>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')
Si está buscando agregar a una lista, pruebe esto:
>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']
169
Author: Matt Williamson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-18 00:36:57
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-18 00:36:57
En el caso de enteros que se incluyen en la cadena, si desea evitar enviarlos a int
individualmente, puede hacer:
mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
Se llama comprensión de lista, y se basa en la notación del constructor de conjuntos.
Ex:
>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]
8
Author: Camilo Celis Guzman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 06:54:47
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 06:54:47
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')
4
Author: Raymond Hettinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-06 19:51:36
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-06 19:51:36