简体   繁体   English

如何将以下Scala代码转换为python

[英]How to convert the following scala code to python

Here is a Pattern matching switch case in Scala, which basically matches different data types of the selector variable to the corresponding case variable and does some manipulation on it 这是Scala中的模式匹配切换用例,它基本上将选择器变量的不同数据类型与相应的用例变量进行匹配,并对它进行一些处理

def valueToString(x: Any): String = x match {

        case d: BigDecimal =>
          /* do something here */

        case a: Array[Byte] =>
          new String(a, "UTF-8")

        case s: Seq[_] =>
          /*do something here */

        case m: Map[_,_] =>
         /*do something here */

        case d: Date =>
          /*do something here */

        case t: Timestamp =>
          /*do something here */

        case r: Row =>
        /*do something here */
       }

Python does not have exactly support this kind of pattern matching. Python并不完全支持这种模式匹配。 I know about switcher in Python, but it expects either regex or actual matching of the variable. 我知道Python中的switcher,但是它期望regex或变量的实际匹配。 How do i achieve the above functionality in Python 如何在Python中实现上述功能

Type checking 类型检查

Use isinstance method to check the type of your generic input 使用isinstance方法检查通用输入的类型

import datetime

def value_to_string(input):

    # String
    if isinstance(input, basestring):
        return 'string'

    # BigDecimal
    if isinstance(input, int):
        return 'int'

    # Array
    if isinstance(input, list):
        return 'list'

    # Map
    if isinstance(input, dict):
        return 'dictionary'

    # Date
    if isinstance(input, datetime.date):
        return 'date'

    # ...

usage 用法

print value_to_string('')
print value_to_string(1234)
print value_to_string([1,2,3])
print value_to_string({"id": 1})
print value_to_string(datetime.datetime.now())

output 产量

string
int
list
dictionary
date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM