用Python编写Type函数

我一直在尝试编写一个函数mytype(v),该函数执行与type()相同的操作,并且可以识别整数,浮点数,字符串和列表。有人指示我先使用str(v),然后再读取字符串。我快完成了,但是当我在mytype中输入一个集合,即mytype({1,2})时,我需要使该函数将其识别为字符串,但它一直说它是一个列表。我想知道如何修复我的代码,以便该函数将集合识别为字符串,而不是列表。这是我到目前为止的内容:

def mytype(v):

 s = str(v)

    import re

    # 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'>"

    # anything that's not an int,float or list
    return "<type 'string'>" 
WANGpingping456 回答:用Python编写Type函数

您的正则表达式也是 通用。

例如,r'[\[\]]'实际上将匹配包含[]所有,因此以下输入为匹配项:'foobar[barfoo'

您应该使用anchors

def mytype(v):

    s = str(v)

    import re

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

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

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

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

一些测试:

> mytype([])
"<type 'list'>"

> mytype(['a','b',3])
"<type 'list'>"

> mytype(1.0)
"<type 'float'>"

> mtype(1.)
"<type 'float'>"

> mytype(123)
"<type 'int'>"

> mytype({1,2})
"<type 'string'>"

> mytype({'foo': 'bar'})
"<type 'string'>"
本文链接:https://www.f2er.com/3169771.html

大家都在问