从列表python中删除特定字符

时间:2021-04-07 20:26:28

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

我是Python的新手。我有一个列表如下:

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?

但这需要我创建两个新列表,我不想更改我的原始列表。您能否建议一个简单的方法,以便我可以修改我的原始列表而无需创建新列表?

1 个解决方案

#1


8  

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)]

#1


8  

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)]