python - 使用正则表达式确定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'>
解决方案
用于在正则表达式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'>
推荐阅读
- r - R Plot Bars 在 grid.arrange/plot_grid 中消失
- node.js - brew 无法在 mac os big sur 上安装节点
- reactjs - 如何使用 React js 传递来自不同组件的值
- python - 如何根据索引位置划分列表?
- python - 在一天中的特定时间使用 gunicorn 运行 Web 应用程序的最佳方式是什么?
- scala - 在两个演员之间使用 pipeTo 时得到 akka 死信
- elasticsearch - 如何在 elastalert 规则中使用通配符
- active-directory - 将自定义属性添加到用户模式失败的 LDF
- f# - F# 中的元组与 * 星型类型
- javascript - Bootstrap - 以特定方式缩放图像