I would like to convert mystring into list.
Input : "(11,4) , (2, 4), (5,4), (2,3) "
Output: ['11', '4', '2', '4', '5', '4', '2', '3']
>>>mystring="(11,4) , (2, 4), (5,4), (2,3)"
>>>mystring=re.sub(r'\s', '', mystring) #remove all whilespaces
>>>print mystring
(11,4),(2,4),(5,4),(2,3)
>>>splitter = re.compile(r'[\D]+')
>>>print splitter.split(mystring)
['', '11', '4', '2', '4', '5', '4', '2', '3', '']
In this list first and last element are empty. (unwanted)
Is there any better way to do this.
Thank you.
>>> re.findall(r'\d+', "(11,4) , (2, 4), (5,4), (2,3) ")
['11', '4', '2', '4', '5', '4', '2', '3']
最好删除空格和圆括号,然后简单地以逗号分隔。
>>> alist = ast.literal_eval("(11,4) , (2, 4), (5,4), (2,3) ")
>>> alist
((11, 4), (2, 4), (5, 4), (2, 3))
>>> anotherlist = [item for atuple in alist for item in atuple]
>>> anotherlist
[11, 4, 2, 4, 5, 4, 2, 3]
Now, assuming you want list elements to be string, it would be enough to do:
>>> anotherlist = [str(item) for atuple in alist for item in atuple]
>>> anotherlist
['11', '4', '2', '4', '5', '4', '2', '3']
The assumption is that the input string is representing a valid python tuple, which may or may not be the case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.