簡體   English   中英

“Pythonic”等效於處理開關和多字符串比較

[英]“Pythonic” equivalent for handling switch and multiple string compares

好吧,所以我的頭銜糟透了。 一個例子效果更好:

input = 'check yahoo.com'

我想解析輸入,使用第一個單詞作為“命令”,並將字符串的其余部分作為參數。 這是我的非Pythonic思想編碼的簡單版本:

if len(input) > 0:
    a = input.split(' ')
    if a[0] == 'check':
        if len(a) > 1:
            do_check(a[1])
    elif a[0] == 'search':
        if len(a) > 1:
            do_search(a[1])

我喜歡Python,因為它將通常很復雜的東西變成了相當簡單的東西。 我對它沒有太多的經驗,而且我相信有更好的方法來做這些事情...某種程度上更加詭異。 我已經看到一些人用dicts和lambda函數替換switch語句的例子,而其他人只是推薦if..else嵌套。

dispatch = {
  'check': do_check,
  'search': do_search,
}
cmd, _, arg = input.partition(' ')
if cmd in dispatch:
    dispatch[cmd](arg)
else:
    do_default(cmd, arg)

我相當確定有更好的方法來做這些事情...某種方式更加pythonic。

並不是的。 你的代碼簡單,清晰,明顯,像英文一樣。

我見過一些用dicts和lambda函數替換switch語句的例子,

是的,你已經看過他們了,他們不清楚,明顯或類似英語。 它們的存在是因為有些人喜歡在switch語句上絞盡腦汁。

而其他人只是推薦if..else巢。

正確。 他們工作。 它們簡單明了,......

你的代碼很好。 不要管它。 繼續。

這樣可以避免兩次給出每個命令名稱; 函數名幾乎直接用作命令名。

class CommandFunctions:
    def c_check(self, arg):
        print "checking", arg

    def c_search(self, arg):
        print "searching for", arg

    def c_compare(self, arg1, arg2):
        print "comparing", arg1, "with", arg2

    def execute(self, line):
        words = line.split(' ')
        fn = getattr(self, 'c_' + words[0], None)
        if fn is None:
            import sys
            sys.stderr.write('error: no such command "%s"\n' % words[0])
            return
        fn(*words[1:])

cf = CommandFunctions()
import sys
for line in sys.stdin:
    cf.execute(line.strip())

如果您正在尋找一種單線“pythonic”方法,您可以使用:


def do_check(x): print 'checking for:', x
def do_search(x): print 'searching for:', x

input = 'check yahoo.com'
{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])
# checking for: yahoo.com

input = 'search google.com'
{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])
# searching for: google.com

input = 'foo bar.com'
{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])
# searching for: bar.com

無視,我剛剛意識到我的答案與其他答案類似 - 顯然沒有刪除密鑰:)

@ MizardX答案的變化:

from collections import defaultdict

dispatch = defaultdict(do_default, check=do_check, search=do_search)
cmd, _, arg = input.partition(' ')
dispatch[cmd](arg)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM