将带有True / False语句的if / else块转换为字典

时间:2016-11-17 17:17:47

标签: python python-3.x dictionary

我正在遍历字符串中的字符,我想确定每个字符的类型。

这可以通过if / else块来完成:

    if char.isdigit():
        char_type = 'number'
    elif char.isalpha():
        char_type = 'letter'
    elif char in {'*', '/', '+', '-', '='}:
        char_type = 'operator'
    else:
        char_type = 'other'

如果代码是这样的:

    if val == 1:
        char_type = 'number'
    elif val == 2:
        char_type = 'letter'
    elif val == 3:
        char_type = 'operator'

字典可能是:

d = {1: 'number', 2: 'letter', 3: 'operator'}

但在这种情况下,每个陈述都是TrueFalse。这可以转换成字典吗?

3 个答案:

答案 0 :(得分:1)

是的,您可以使用d[char]语法,但它几乎不值得花费复杂性和可读性。

您可以将if/else封装在类的__getitem__方法中,然后使用[]语法检索字符类型,如下所示:

class CharType:
    def __getitem__(self, char):
        if char.isdigit():
            char_type = 'number'
        elif char.isalpha():
            char_type = 'letter'
        elif char in {'*', '/', '+', '-', '='}:
            char_type = 'operator'
        else:
            char_type = 'other'
        return char_type

d = CharType()

print(d["a"], d["+"])

答案 1 :(得分:0)

是的,您可以设置字典来完成所有工作。设置完成后,您可以非常快速地运行大量文本:

import string

type_dictionary = dict()
type_dictionary.update({c: 'letter' for c in string.ascii_letters})
type_dictionary.update({c: 'number' for c in string.digits})
type_dictionary.update({c: 'operator' for c in {'*', '/', '+', '-', '='}})

string = "elif val == 3:"

for character in string:
    print(character, "->", type_dictionary.get(character, 'other'))

输出

e -> letter
l -> letter
i -> letter
f -> letter
  -> other
v -> letter
a -> letter
l -> letter
  -> other
= -> operator
= -> operator
  -> other
3 -> number
: -> other

另一种方法是使用字符转换表:

import string
import itertools

type_dictionary = {'1': 'number', '2': 'letter', '3': 'operator', '4': 'other'}

maketrans_dictionary = dict({c: '4' for c in string.printable})
maketrans_dictionary.update({c: '2' for c in string.ascii_letters})
maketrans_dictionary.update({c: '1' for c in string.digits})
maketrans_dictionary.update({c: '3' for c in {'*', '/', '+', '-', '='}})

table = str.maketrans(maketrans_dictionary)

string = "elif val == 3:"

for character, character_type in zip(string, string.translate(table)):
    print(character, "->", type_dictionary[character_type])

以上两者都不是Unicode友好的,没有额外的工作,但我认为这不是问题,因为char in {'*', '/', '+', '-', '='}都不是。

答案 2 :(得分:-1)

根据我的问题理解。

s="abcd12e+"
dic={}
for i in s:
    if i.isdigit():
        dic[i]="digit"
    elif i.isalpha():
        dic[i]="alpha"
    elif i in ['*', '/', '+', '-', '=']:
        dic[i]="operator"
    else:
        dic[i]="other"
print dic

示例字符串输出为: {'a':'alpha','c':'alpha','b':'alpha','e':'alpha','d':'alpha','+':'operator',' 1':'数字','2':'数字'}

相关问题