Skip to main content
 首页 » 编程设计

python之使用正则表达式确定python中变量的类型

2024年12月31日30lidabo

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

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

这个问题需要使用正则表达式。 这是我到目前为止所拥有的,据我所知它是有效的。 我想知道是否有办法在没有这么多 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'> 

请您参考如下方法:

使用 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'> 

Code demo