Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用re转换list get元素的最常用的Pyhthonic方法_Python_Regex_List_Integer - Fatal编程技术网

Python 用re转换list get元素的最常用的Pyhthonic方法

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

我使用正则表达式从字符串(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.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))
?谢谢。然后我会读更多关于地图的内容。再次感谢,谢谢。您必须遵守《联合国宪章》;)