【发布时间】:2019-02-01 22:26:55
【问题描述】:
我是 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'>
【问题讨论】:
-
嘿!根据您在描述中提出的限制,我不确定您是否应该考虑效率,无论哪种方式,为了使您的代码更短,您可以使用
for语句遍历不同的 reg 表达式并尝试在您的字符串。 -
你应该刷你的正则表达式(例如你的列表匹配 "[bla" 或 "][" 这可能不是你想要的。你可以通过将正则表达式与元组中的结果配对来避免 ifs 和遍历它们。
-
如前所述,您的正则表达式太抢眼了。除了括号之外,
"5.5.5"也将被检测为浮点数,而“xyz23"则被检测为 int。请确保标记边界/开始和结束以确保正则表达式正确匹配。 -
顺便说一句,您的问题可能更适合 StackExchange :: Code Review。 (只是一个想法)
标签: python regex python-2.x