You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
Copylist1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()
If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort takes a named parameter, key, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:
Copylist1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)
# or if you want to do it all in the same line
list1 = sorted([int(x) for x in list1])
Answer from Seamus Campbell on Stack Overflowsorting list of strings that start with numbers
How do I sort the numbers in a given string?
array - Sort numbers in ascending order using Python - Code Review Stack Exchange
sorted() vs sort()
Videos
You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
Copylist1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()
If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort takes a named parameter, key, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:
Copylist1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)
# or if you want to do it all in the same line
list1 = sorted([int(x) for x in list1])
I approached the same problem yesterday and found a module called natsort, which solves your problem. Use:
Copyfrom natsort import natsorted # pip install natsort
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
# Your array may contain strings
[In] natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']
It also works for dictionaries as an equivalent of sorted.
I have a list that is something like this:
Rankings = [1174 apple, 22 banana, 3 pear]
Sorted_rankings=Rankings.sort(?????)
How would I sort that so they are sorted by the numbers?
EX: string="abcd7efgh14ijkl5mn3op"
how can i sort it to be "abcd3efgh5ijkl7mn14op"
You could combine your input to a single line to improve ease of use. For example,
storage = input("Enter values separated by spaces:")
storage = [int(x) for x in storage.split()]
This way you have the entire list of input and can avoid having to have the user enter the number of input, and avoid having to declare the num variable at all.
However, you probably also want to include some form of input validation or throw a meaningful error as right now if your user was to enter non-integers, your program would simply crash and output a vague error that the user would probably have a difficult time understanding.
try:
storage = [int(x) for x in test.split()]
except ValueError:
print("Non-integers in input!")
Alternatively, you could check if all the values are numeric and if not, have the user re-enter their input.
As for your sorting algorithm, if you don't want to use Python's implemented sort() or sorted(), you should research more efficient algorithm's such as quick sort or even implement the bubble sort that you learned.
Currently, your min_sort algorithm finds the minimum value in the list, which is O(n) then removes that element from the list (separately from the search) which is again O(n). This is extremely wasteful as you may end up searching through the entire list again and again (n times), so it would be better to use a more efficient sorting algorithm or at least recognize that we don't need to pass through the entire list twice on each iteration, just pass through the list once and keep track of the minimum value. You could do this by writing your own function like:
def find_remove_min(nums):
"""Returns the minimum number and the list without the min number"""
if nums:
min_index = 0
for i in range(1, len(nums)):
if nums[i] < nums[min_index]:
min_index = i
return nums[min_index], nums[:min_index] + nums[min_index+1:]
Then you could do something like,
while storage:
min_num, storage = find_remove_min(storage)
result.append(min_num)
which would be more readable and efficient imo.
The built-in sorted(), which uses Timsort, is always preferable, but since you said you were learning bubble sort, I would stick with it even though it is too slow and mutate the input list instead of creating a new one.
numbers = input("Enter numbers separated by a comma: ")
numbers = [int(n) for n in numbers.split(',')]
end = len(numbers) - 1
while end != 0:
for i in range(end):
if numbers[i] > numbers[i + 1]:
numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
end = end - 1
Running it:
Enter numbers separated by a comma: 3, 0, 1, 4, 2
[0, 1, 2, 3, 4]
>>>
So I get that one of the main differences between sorted() and sort() is that sorted() returns a new list and sort() modifies the list directly. But I don't understand why their outputs can't be exactly equal if they print out to being, in fact, exactly equal. For example:
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(f"Sorted list: {sorted_numbers}")
numbers.sort()
print(f"Sorted list: {numbers}")
print(numbers.sort() == sorted(numbers))This is the output:
Sorted list: [1, 1, 2, 3, 4, 5, 9] Sorted list: [1, 1, 2, 3, 4, 5, 9] False
As we can see, both sorted(numbers) and numbers.sort return what appears to be identical output: [1, 1, 2, 3, 4, 5, 9]. Of course, sort() has modified the original list, so that object has been changed by the end of the program. But if these two outputted lists are clearly identical from a mathematical perspective (ie: [1, 1, 2, 3, 4, 5, 9] == [1, 1, 2, 3, 4, 5, 9] is true on it's on terms as a standalone expression ) - then why won't Python embrace this apparently same understanding with: print(numbers.sort() == sorted(numbers))?
Is there some unseen object that represents the original list that is lingering unprinted in the background and attached to sorted(numbers)?
Thanks ahead of time for your interest and time on this matters.