首页 > 解决方案 > 使用正则表达式确定python中的变量类型

问题描述

我是 python 新手,想知道是否有更有效的方法来完成这个作业问题:

编写一个函数 mytype(v),它执行与 type() 相同的操作,并且可以识别整数、浮点数、字符串和列表。首先使用 str(v),然后读取字符串。假设列表只能包含数字(不是字符串、其他列表等),并假设字符串可以是任何不是整数、浮点数或列表的东西。

该问题需要使用正则表达式。这是我到目前为止所拥有的,据我所知它是有效的。我想知道是否有办法在没有这么多 if 语句的情况下做到这一点?即更简洁或更高效?

import re 

def mytype(v):
   s = str(v)
   # Check if list
   list_regex = re.compile(r'[\[\]]')
   l = re.findall(list_regex, s)
   if l:
      return "<type 'list'>"
   # Check if float
   float_regex = re.compile(r'[0-9]+\.')
   f = re.findall(float_regex, s)
   if f: 
      return "<type 'float'>"
   # Check if int
   int_regex = re.compile(r'[0-9]+')
   i = re.findall(int_regex, s)
   if i:
      return "<type 'int'>"
   # Check if string
   str_regex = re.compile(r'[a-zA-Z]+')
   t = re.findall(str_regex, s)
   if t:
      return "<type 'string'>"


x = 5
y = 5.5
z= .99
string = "hsjjsRHJSK"
li = [1.1,2,3.2,4,5]


print mytype(x) # <type 'int'>
print mytype(y) # <type 'float'>
print mytype(z) # <type 'float'>
print mytype(string) # <type 'string'>
print mytype(li) # <type 'list'>

标签: pythonregexpython-2.x

解决方案


用于在正则表达式group中匹配并获取捕获的组名和管道|

正则表达式(?P<list>\[\[^\]\]+\])|(?P<float>\d*\.\d+)|(?P<int>\d+)|(?P<string>\[a-zA-Z\]+)

细节:

  • |或者
  • (?P<>)python命名捕获组

Python代码:

def mytype(v):
    s = str(v)
    regex = re.compile(r'(?P<list>\[[^]]+\])|(?P<float>\d*\.\d+)|(?P<int>\d+)|(?P<string>[a-zA-Z]+)')
    return  r"<type '%s'>" % regex.search(s).lastgroup

输入:

print(mytype(5))
print(mytype(5.5))
print(mytype(.99))
print(mytype("hsjjsRHJSK"))
print(mytype([1.1,2,3.2,4,5]))

输出:

<type 'int'>
<type 'float'>
<type 'float'>
<type 'string'>
<type 'list'>

代码演示


推荐阅读