2011-05-19 53 views
1

我希望寫一個函數foo生成以下的輸出:混合整數和列表

 
foo(0) -> "01 00" 
foo(1) -> "01 01" 
foo([0]) -> "01 00" 
foo([1]) -> "01 01" 
foo([0,1]) -> "02 00 01" 
foo([0,1,10]) -> "03 00 01 0a" 

你將如何實現這一點?我是否需要明確說明爭論的類型?

十六進制(值)[2:]可用於根據需要轉換爲十六進制。

謝謝!

巴里

+0

作業? ..... – Macke 2011-05-19 12:28:18

+1

以下任何答案都有幫助嗎? – Johnsyweb 2011-05-20 07:52:30

回答

3

如果參數是一個int,使之成爲list。然後你可以繼續你的列表處理...

>>> def foo(x): 
...  hexify = lambda n: hex(n)[2:].zfill(2) 
...  if not isinstance(x, list): 
...   x = [x] 
...  return hexify(len(x)) + ' ' + ' '.join(map(hexify, x)) 
... 
>>> foo(0) 
'01 00' 
>>> foo(1) 
'01 01' 
>>> foo([0]) 
'01 00' 
>>> foo([1]) 
'01 01' 
>>> foo([0,1]) 
'02 00 01' 
>>> foo([0,1,10]) 
'03 00 01 0a' 
2

你需要做一些類型檢查。這一切都取決於你想要接受的。

通常,您可以在list構造函數中包裝一些東西,並從中獲取一個列表。

def foo(x): 
    x = list(x) 

但是轉換完全取決於list。例如:list({1: 2})不會給你[2],但[1]

所以,如果你想保護用戶免受意外,你應該檢查輸入是單個整數還是列表。與iterables

>>> isinstance("hej", int) 
False 
>>> isinstance("hej", (int, list)) 
False 
>>> isinstance([1,2,3], (int, list)) 
True 
>>> isinstance(1, (int, list)) 
True 

另外一個問題,你不能保證每一個成員是同類型的,例如:

你可以用isinstance檢查這

[1, 'hello', (2.5,)] 

我只是想嘗試把每個項目,如果不可能,請將雙手舉起,並向使用者抱怨。

2
def tohex(n): 
    ''' Convert an integer to a 2-digit hex string. ''' 
    hexVal = hex(n)[2:] 
    return hexVal.rjust(2, '0') 

def foo(input): 
    # If we don't get a list, wrap whatever we get in a list. 
    if not isinstance(input, list): 
     input = [input] 

    # First hex-value to write is length 
    result = tohex(len(input)) 

    # Then we write each of the elements 
    for n in input: 
     result += " " + tohex(n) 

    return result