Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific characters from list python

Tags:

python

regex

I am fairly new to Python. I have a list as follows:

sorted_x = [('pvg-cu2', 50.349189), ('hkg-pccw', 135.14921), ('syd-ipc', 163.441705), ('sjc-inap', 165.722676)]

I am trying to write a regex which will remove everything after the '-' and before the ',', i.e I need the same list to look as below:

[('pvg', 50.349189), ('hkg', 135.14921), ('syd', 163.441705), ('sjc', 165.722676)]

I have written a regex as follows:

for i in range(len(sorted_x)): 

  title_search = re.search('^\(\'(.*)-(.*)\', (.*)\)$', str(sorted_x[i]), re.IGNORECASE)
     if title_search:
         title = title_search.group(1)
         time = title_search.group(3)

But this requires me to create two new lists and I don't want to change my original list. Can you please suggest a simple way so that I can modify my original list without creating a new list?

like image 221
wanab_geek Avatar asked Feb 17 '23 06:02

wanab_geek


1 Answers

result = [(a.split('-', 1)[0], b) for a, b in sorted_x]

Example:

>>> sorted_x = [('pvg-cu2', 50.349189), ('hkg-pccw', 135.14921), ('syd-ipc', 163.441705), ('sjc-inap', 165.722676)]
>>> [(a.split('-', 1)[0], b) for a, b in sorted_x]
[('pvg', 50.349189000000003), ('hkg', 135.14921000000001), ('syd', 163.44170500000001), ('sjc', 165.72267600000001)]
like image 112
Andrew Clark Avatar answered Mar 03 '23 08:03

Andrew Clark