0

Having trouble sorting a list with str and int. I want my code to return only listing int in asd and excluding str.

def data(data_list):
   for i, n in enumerate(data_list):
      mn = min(range(i,len(data_list)), key=data_list.__getitem__)
      data_list[i], data_list[mn] = data_list[mn], n
    return data_list
data([8,11,10,9,4,3])
#returns this
[3, 4, 8, 9, 10, 11] # which is great but when the list includes str it does not run 
#trying to run this 
data([8,11,'b',9,4,'a'])
# want to return this 
[3, 4, 8, 9]

#Also my code is quite confusing. I am sure there is a simpler way
2
  • 1
    Does this answer your question? Is there a way to output the numbers only from a python list? Commented Oct 14, 2020 at 2:08
  • Make a list that only contains the integers, and then sort it. "I am sure there is a simpler way" The sorted function, and sort method of lists, are built-in. You do not need to implement sorting logic yourself. Commented Oct 14, 2020 at 2:09

3 Answers 3

2

You can simply use the built-in sorted() function and filter out items that are not integers using a list comprehension like so:

>>> datastr = [8, 11, 'b', 9, 4, 'a']
>>> sorted([v for v in datastr if isinstance(v, int)])
[4, 8, 9, 11]
Sign up to request clarification or add additional context in comments.

1 Comment

is there a way to pull an int inside a string. so for example if the datastr= [8, 11, 'b', 9, 4, '2'] it will return [2, 4, 8, 9, 11]
0

You can use isinstance(i, int) to check if a particular object is of type int.

def data(data_list):
  return sorted([o for o in data_list if isinstance(o, int)])

If any on the numbers are strings, you can deal with them using a helper function like below

def intHelper(o):
  if isinstance(o, int):
    return o
  elif isinstance(o, str):
    try:
      return int(o)
    except ValueError:
      return None
  
  return None

def data(data_list):
  return sorted([o for o in list(map(intHelper, data_list)) if o is not None])

Comments

0
data = ['5',4,3,2,1.1,'zero','-1','0.4']
sorted_data = []
for datum in data:
    try:
        if isinstance(datum,str):
            if '.' in datum:
                sorted_data.append(float(datum))
            else:
                sorted_data.append(int(datum))
        else:
            if isinstance(datum,int):
                sorted_data.append(int(datum))
            else:
                sorted_data.append(float(datum))
    except:
        pass

sorted_data.sort()
print(sorted_data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.