2012-07-03 62 views
2

假設我有一串由可變長度的逗號分隔的整數。如果分隔字符串和使用值更新變量(如果它們存在),最好的方法是什麼?從可變長度字符串解析值的最佳方法是什麼?

目前,我有以下幾點。

a, b, c = 10, 10, 1 #default values 
mylist = [int(x) for x in input.split(',')] 
if len(mylist) == 2: a, b = mylist 
else: a, b, c = mylist 

有沒有更有效的方法呢?

+0

之前;請注意,OP現在要使用默認值。 –

+0

這是[在Python中將可變長度字符串拆分爲變量的最佳方法是什麼?](http://stackoverflow.com/questions/11313256/what-is-the-best-way-to -split-a-variable-length-string-into-variables-in-python) –

+0

@idealistikz:對於你所要求的,代碼是足夠高效的IMO。我想不出一種方法來提高你正在做的事情的速度。你能提供一個上下文還是更多的代碼? –

回答

5
a, b, c = 10, 10, 1 #default values 
mylist = [int(x) for x in input.split(',')] 
a, b, c = mylist + [a, b, c][len(mylist):] 

我認爲這是醜陋的原因是,它是不符合Python在總治療局部變量;實例成員會更合適。

+0

你需要在listcomp中有'if x'作爲空輸入。 – jfs

+0

@astynax:如果'len(mylist)> 3'是一個功能而不是bug,則引發異常。 – jfs

1
defaults=[10,10,1] 
mylist=[int(x) for x in ipt.split(',')] 
defaults[:len(mylist)]=mylist 
a,b,c=defaults 

這改變defaults雖然...你避免這種情況,像這樣的工作:

defaults=[10,10,1] 
mylist=[int(x) for x in ipt.split(',')] 
temp_defaults=defaults[:] 
temp_defaults[:len(mylist)]=mylist 
a,b,c=temp_defaults 

此外,使用input作爲變量名要小心。它是內置python的名稱,因此您可以輕鬆訪問該功能。

+0

這比原來的方法更有效嗎? – idealistikz

+0

@idealistikz - 以什麼方式提高效率?計算速度?我不知道。你可以用'timeit'來計時。 – mgilson

1

使用切片到用戶輸入與默認的參數列表相結合:

>>> defaults = [10, 10, 1] 
>>> user_input = '15 20' 
>>> user_ints = map(int, user_input.split()) 
>>> combined = user_ints + defaults[len(user_ints):] 
>>> a, b, c = combined 
3

你可以使用一個輔助功能:

def f(a=10, b=10, c=1): 
    return a, b, c 

a, b, c = f(*map(int, input.split())) 

這會不會是快 - 它只是用不同的方式來做到這一點,僅僅越過我的腦海。

0

izip_longest允許採用默認值的長度,如果較長的:任何人都關閉此作爲欺騙

>>> from itertools import izip_longest 
>>> inp = '3, 56' 
>>> a, b, c = [i if i else j for i, j in izip_longest([int(x) for x in inp.split(',')], (10, 10, 1))] 
>>> a, b, c 
(3, 56, 1) 
0
a, b, c = (map(int, user_input.split(',')) + [20,20,10])[:3] 

def parse(user_input, *args): 
    return (map(int, user_input.split(',')) + list(args))[:len(args)] 

>>> a, b, c = parse('1,2', 20, 20, 10) 
>>> a, b, c 
(1, 2, 20) 
>>> a, b, c, d = parse('1,2,3,4,5', 0, 0, 0, 0) 
>>> a, b, c, d 
(1, 2, 3, 4) 
相關問題