0

整数のインクリメントまたはデクリメント、文字列への文字の追加など、特定のユーザー入力に対して特定のタスクを実行するプログラムを作成しようとしています。
ユーザーは同じ行に複数のコマンドを与えることができます。

を使用してraw_inputいるため、複数行の入力を使用できません (また、使用したくありません)。

if-elif-else条件文を短くして、読みやすい形式にすることはできますか ?

for i in test_str:
    if i == '[':
        a += 1
    elif i == '(':
        b += 1
    elif i == ']' and c > 0:
        c -= 1
    elif i == ')'and d > 0:
        d -= 1
    elif c == 0 and d == 0:
        ret += i
    ... # more elifs

likeの可能性もありますelif:

elif i == 'o':
    if test_str[test_str.index(i)+1] == i: # next char is same
         # handle
    else:
         # handle

これを解析に使用しています。

4

1 に答える 1

0

コードで使用する行数を減らしたい場合はif - elif - else、1 行で簡単にステートメントを実行できます。

if i == '[':
    a += 1
elif i == '(':
    b += 1
elif i == ']' and c > 0:
    c -= 1
elif i == ')'and d > 0:
    d -= 1
elif c == 0 and d == 0:
    ret += i

なる:

if i == '[': a += 1   
elif i == '(': b += 1   
elif i == ']' and c > 0: c -= 1   
elif i == ')'and d > 0: d -= 1    
elif c == 0 and d == 0: ret += i

ただし、これを行う代わりに、使用しているロジックを変更する必要があります。

まず第一に、関数を使用する必要があります。また、ある種のマッピングもお勧めします。

例:

d = {
'[' : ('add', a, 1),
'(' : ('add', b, 1),
']' : ('method', my_method, ['sample_arg1', 'sample_arg2'], {'sample_kwarg' : 'sample value'})} 

def check_char(char, mapping):
    mapper = d.get(char, None)
    if mapper:
        if mapper[0] == 'add':
            mapper[1] += mapper[2]
        if mapper[0] == 'subtract':
            mapper[1] -= mapper[2]
        if mapper[0] == 'method':
            mapper[1](char, mapper[2], mapper[3])
    # you get the idea....

def my_method(char, *args, **kwargs):
    # deal with char....
于 2013-02-13T10:37:58.797 に答える