Skip to main content
 首页 » 编程设计

python之当由 '..' Python 分隔时,将两个整数附加到列表

2025年05月04日11www_RR

如果我有一个列表字符串:

first = [] 
last = [] 
 
my_list = ['  abc   1..23',' bcd    34..405','cda        407..4032'] 

我如何将 .. 两侧的数字附加到它们相应的列表中?得到:

first = [1,34,407] 
last = [23,405,4032] 

我也不介意字符串,因为我稍后可以转换为 int

first = ['1','34','407'] 
last = ['23','405','4032'] 

请您参考如下方法:

使用re.search匹配 .. 之间的数字并将它们存储在两个不同的组中:

import re 
 
first = [] 
last = [] 
 
for s in my_list: 
  match = re.search(r'(\d+)\.\.(\d+)', s) 
  first.append(match.group(1)) 
  last.append(match.group(2)) 

DEMO .