简体   繁体   中英

How to determine if variable is int or list for loop in Python

I want to write a function that takes either an int or a list of int as parameter and processes that values.

something like that:

def func(input):
  if isinstance(input, int):
    print(input)
  else:
    for i in input:
      print(i)

this doesn't look very pythonic to me, but I don't know how to do it better. Is there a way to "loop" over the int or "pack" the int into a list that handles both options

Thanks

You can also follow the pythonic principle EAFP ( Easier to ask for forgiveness than permission )

def func(your_input):
    try:
        for i in your_input:
            print(i)
    except TypeError:
        print(your_input)

You try to iterate for entries in input and print them. If type of input is not iterable (like an int ), then trying to iterate over a non-iterable object raises a TypeError exception. In the except clause you can then print the input.

EDIT : As @buran noted, input is a reserved keyword for Python, so you should avoid it.

I wouldn't worry so much about it being Pythonic or not. But here is another way you could do it that doesn't restrict you to lists or ints, but rather checks if you have an iterable or not:

def func(input):
    if not hasattr(input, '__iter__'):
        input = [input]

    for i in input:
        print(i)

But another potentially cleaner option to consider could be this:

def func(*inputs):
    for i in inputs:
        print(i)

You would call this function slightly differently: func(5) for scalars and func(*lst) for iterables.

For sake of completeness, in addition to @jcf answer, you can use functoools.sigledispatch (or functools.singledispatchmethod if in class) it allows to overload function with different implementation, depending on type of first argument

from functools import singledispatch

@singledispatch
def func(foo):
    print(foo)

@func.register(list)
def _(foo):
    for item in foo:
        print(item)

func(1)
func([2, 3, 4])

Now, the question is what you do if you get something different from list, like tuple, or generator, etc. You may want to use abstract classes from collections.abc instead of list

On a side note - don't use input as name - it's a built-in function.

def func(input):
    for i in ([input] if isinstance(input, int) else input):
        print(i)

"packs" an int into a list as you wanted, but I don't think it is any more elegant than your original code.

if type(input) == int:
    print('Integer')
    # Do integer operation
elif isinstance(input, list):
    print('List')
    # Do list operation 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM