Python 用re转换list get元素的最常用的Pyhthonic方法
我使用正则表达式从字符串(lp)中提取一些数字。我知道我将从中得到的列表只包含2个元素。我也知道它们都是整数 因此,我只想用一行代码来写这篇文章Python 用re转换list get元素的最常用的Pyhthonic方法,python,regex,list,integer,Python,Regex,List,Integer,我使用正则表达式从字符串(lp)中提取一些数字。我知道我将从中得到的列表只包含2个元素。我也知道它们都是整数 因此,我只想用一行代码来写这篇文章 home,away = re.findall(r'\d+',lp) home,away = int(home),int(away) 感谢您的帮助您可以使用以下功能: home, away = map(int, re.findall(r'\d+', lp)) 另一个想法是使用列表理解: home, away = [int(e) for e in re
home,away = re.findall(r'\d+',lp)
home,away = int(home),int(away)
感谢您的帮助您可以使用以下功能:
home, away = map(int, re.findall(r'\d+', lp))
另一个想法是使用列表理解:
home, away = [int(e) for e in re.findall(r'\d+', lp)]
使用静态结果长度时管理类型的小技巧:
expected_types = [int, int, str]
elements = ['1', '2', 'toto']
result = [_type(e) for _type, e in zip(exected_types, elements]
# Returns : [1, 2, 'toto']
另一个解决方案:
home,away=[int(x)代表re.findall(r'\d+',lp)中的x]
编辑:FunkySayu你更快了…
map(int,re.findall(r'\d+',lp))
?谢谢。然后我会读更多关于地图的内容。再次感谢,谢谢。您必须遵守《联合国宪章》;)