这样的条件判断语句有哪些pythonic的写法
阿神
阿神 2017-04-17 18:00:52
0
4
356

代码如下:

def text2number(str):
    if '褒' in str:
        return 1
    elif '贬' in str:
        return -1
    else:
        return 0
阿神
阿神

闭关修行中......

reply all(4)
洪涛
text2number = lambda string: 1 if '褒' in string else -1 if '贬' in string else 0

In addition, it is not recommended that you use built-in method names as parameters. .

阿神
def text_to_id(text):
    mapping = {
       '褒': 1,
       '贬': -1,
    }
    return mapping.get(text, 0)

Shorter words:

def text_to_id(text):
    return {
       '褒': 1,
       '贬': -1,
    }.get(text, 0)

If it were shorter:

text_to_id = lambda text: {
    '褒': 1,
    '贬': -1,
}.get(text, 0)

I also want to say that it is not recommended to use built-in class names str as parameter names.

PHPzhong

You mean

1 if str.find('褒')!=-1 else -1 if str.find('贬')!=-1 else 0

Is this a trend

Available in actual testing, but not recommended

黄舟

def text2number(str):

if not isinstance(str, unicode):
    str = str.decode('utf-8')
if u'褒' in str:
    return 1
if u'贬' in str:
    return -1
return 0
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!