\"01 01\"" />
开发者

Mixing ints and lists

I wish to write a function foo to produce the following output:

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"

How would you implement this? Do I need to explicitly the type of the arguemnt?

hex(value)[2:] can be used to convert to h开发者_运维知识库ex as required.

Thanks!

Barry


If the argument is a single int, make it a list. Then you can continue with your list processing...

>>> 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'


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


You will need to do some type checks. It all depends on what you want to accept.

Generally, you can wrap something in the list constructor and get a list from it.

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

But the conversion depends entirely on list. For example: list({1: 2}) will not give you [2] but [1].

So if you want to protect the user from surprises you should perhaps check if the input is a single integer or a list.

You can check this with isinstance:

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

Another problem with iterables, you cannot guarantee every member is of the same type, for example:

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

I would just try converting each item to a number, if not possible, throw your hands up in the air and whine to the user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜