Home > Blockchain >  Searching for a string character in a list with different types of values
Searching for a string character in a list with different types of values

Time:10-26

I have a list consisting of different types of values - that is, ints and strings. I want to use a loop to find character indexes that are not numbers.

#for a list
list = [2, 3, 4, '*', 2, '^', ' ']
#Output should look like this
3, 5, 6

CodePudding user response:

Try list comprehension using the built-in function type

lst = [2, 3, 4, '*', 2, '^', ' ']
out = [idx for idx,val in enumerate(lst) if type(val) == str]  # -> [3, 5, 6]

CodePudding user response:

For ints only, you can do something like

[idx for idx,val in enumerate(lst) if type(val) != int]

Later, you said "not numbers". For that, there are few options - one uses the answer here to check if a value is a number: https://stackoverflow.com/a/4187266/2506943

import numbers
[idx for idx,val in enumerate(lst)  if not isinstance(val, numbers.Number)]

CodePudding user response:

You can also use isinstance to check if current item is string.

lst = [2, 3, 4, '*', 2, '^', ' ']
result = []

for i in range(len(lst)):
    if isinstance(lst[i], str):
        result.append(i)
# or use list comprehension
result = [i for i in range(len(lst)) if isinstance(lst[i], str)]

CodePudding user response:

    listA = [2, 3, 4, '*', 2, '^', ' ']
    res=set(listA)
    for i in res:
      if str(i).isalnum()!=True:
         print(listA.index(i))

you can simply use listA instead of converting that to set .

  • Related