Home > Mobile >  Get the type and index of an object in arguments in Python
Get the type and index of an object in arguments in Python

Time:01-13

There are 2 cases in my function, 1: All arguments will be strings there is no problem with this one. 2: There will also be int or floats. What i want to do is, check the types of *vars, if there is int or float type, find the index of this types.

def fonk(comp, *vars):
    varList = []
    varList.append(vars)
    varList = [x for xs in varList for x in xs]
    for i in range(len(varList)):
       if all(isinstance(x, str) for x in varList) == False:
          if type(varList[i]) == int or float:

for example:

fonk(">","str1", 1, "str2", 2.5)

so int and float type would be vars[1] and vars[3]. How can i determine this? Thanks in advance.

CodePudding user response:

def fonk(comp, *vars):
    if not all(isinstance(x, str) for x in varList):
        return [i for i, val in enumerate(vars) if isinstance(val, (int, float))]

There's no need to copy vars to varList, and the all() test should not be inside a loop.

if type(varList[i]) == int or float:

is not the correct way to test if something is equal to one of multiple values. See Why does "a == x or y or z" always evaluate to True?

You can give isinstance() a tuple of types, and it will test if it's an instance of any of them.

CodePudding user response:

To check type you want to check each separately and do the operation according to the type.

def fonk(comp, *vars):
    for var in vars:
        if isinstance(var, str):
            pass
        elif isinstance(var, (int, float)):
            pass
  •  Tags:  
  • Related