【问题标题】:Use regular expressions to determine type of variable in python使用正则表达式确定python中的变量类型
【发布时间】: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


【解决方案1】:

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

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

详情:

  • |
  • (?P&lt;&gt;)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

【讨论】:

  • 这太棒了,我学到了一些新东西。但是,它应该带有一个警告它捕获第一种类型,即'mt5'将返回'string'并且'5mt'将返回'int'
【解决方案2】:

我想知道是否有办法做到这一点而没有这么多 if 声明?即更简洁或更高效?

在不影响你的结果的情况下,更严格地遵守规则,我们可以折腾一个if语句和你的一半代码:

def mytype(v):
    s = str(v)

    # Check if list
    if re.search(r'[\[\]]', s):
        return "<type 'list'>"

    # Check if float
    if re.search(r'[\d]+\.', s): 
        return "<type 'float'>"

    # Check if int
    if re.search(r'[\d]+', s):
        return "<type 'int'>"

    # Assume strings are anything that's not an int, float or list
    return "<type 'string'>"

这甚至在考虑您的正则表达式之前。对于这种用法,您无需致电 re.compile()。您的 list 测试可以轻松捕获 dictdict 不在您的要求中。 z = .99 之所以有效,是因为当它变成字符串时,它是"0.99"".99" 的实际字符串将无法通过您的 float 测试。您的floatint 测试存在顺序依赖关系——应该注释掉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2015-05-01
    • 2016-01-04
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多