简体   繁体   English

Python:-将字符串转换为列表

[英]Python:- Convert a string into list

I have a string like groups(1,12,23,12) and I want to convert it into a list like [1,12, 23, 12] . 我有一个字符串,如groups(1,12,23,12) ,我想将其转换为[1,12, 23, 12] groups(1,12,23,12) [1,12, 23, 12]类的列表。

I tried this code, but output is not as excepted. 我尝试了这段代码,但是输出不是例外。

str = 'groups(1,12,23,12)'
lst = [x for x in str]

Please let me know...! 请告诉我...!

You could use re.findall method. 您可以使用re.findall方法。

And don't use str as variable name. 并且不要使用str作为变量名。

>>> import re
>>> s = 'groups(1,12,23,12)'
>>> re.findall(r'\d+', string)
['1', '12', '23', '12']
>>> [int(i) for i in re.findall(r'\d+', s)]
[1, 12, 23, 12]

Without regex, 没有正则表达式,

>>> s = 'groups(1,12,23,12)'
>>> [int(i) for i in s.split('(')[1].split(')')[0].split(',')]
[1, 12, 23, 12]

For an approach without regex 对于没有正则表达式的方法

>>> a = "groups(1,12,23,12)"
>>> a= a.replace('groups','')
>>> import ast
>>> list(ast.literal_eval(a))
[1, 12, 23, 12]

Ref: 参考:

  1. Use regular expression to find numbers from the input string. 使用正则表达式从输入字符串中查找数字。
  2. Use map method to convert string to integer. 使用map方法将字符串转换为整数。

eg 例如

>>> import re
>>> a = 'groups(1,12,23,12)'
>>> re.findall("\d+", a)
['1', '12', '23', '12']
>>> map(int, re.findall("\d+", a))
[1, 12, 23, 12]
string = "groups(1,12,23,12)".replace('groups(','').replace(')','')
outputList = [int(x) for x in string.split(',')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM