why sort in python is not working? - python

code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?

when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in

I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']

You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list

Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())

I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

Related

Converting Strings to int in List [duplicate]

This question already has answers here:
Convert all strings in a list to int
(10 answers)
Closed last month.
have a list with numeric strings, like so:
numbers = ['1', '5', '10', '8'];
I would like to convert every list element to integer, so it would look like this:
numbers = [1, 5, 10, 8];
The natural Python way of doing this is using list comprehensions:
intlist = [int(element) for element in stringlist]
This syntax is peculiar to the Python language and is a way to perform a "map" with an optional filtering step for all elements of a sequnce.
An alterantive way, which will be more familiar for programmers that know other languages is to use the map built-in: in it, a function is passed as the first parameter, and the sequence to be processed as the second parameter. The object returned by map is an iterator, that will only perform the calculations on each item as it is requested. If you want an output list, you should build a list out of the object returned by map:
numbers = list(map(int, stringlist))
You can use a simple function called map:
numbers = ['1', '5', '10', '8']
numbers = list(map(int, numbers))
print(numbers)
This will map the function int to each element in the iterable. Note that the first argument the map is a function.
you can use generator objects
[int(i) for i in numbers]
Sometimes int() gives convertion error if the input it's not a valid variable. In that case must create a code that wraps all convertion error.
numbers = []
not_converted = []
for element in string_numbers:
try:
number = int(element)
if isinstance(number, int):
numbers.append(number)
else:
not_converted.append(element)
except:
not_converted.append(element)
If you expect that the input it's aways a string int you can simply convert like:
numbers = [int(element) for element in string_numbers]
You can use the below example:-
numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)

list of integers to string

a=[2]
a.append(3)
print (a)
result is [2, 3].
I want to have a output 23 instead of [2,3]. Any suggestions?
When you do something like a = [2] in Python, it creates a list out of it with one element 2 in the list.
You seemingly want string operations. There are two ways to do this. Firstly,
a = '2'
a = a + '3'
print (a)
Another way, probably the one which you're looking for, is converting the list into a string, as follows.
a = [2]
a.append(3)
b = ''.join(str(x) for x in a)
print (b)
Here is a brief explanation of the second approach:
You forcibly typecast each element of the list a to string, and then use join method to convert the list to string. Essentially, first the list [2, 3] is converted to ['2', '3'] and then join is used.
Edit:
Another approach, to better explain what I said above,
a = [str(2)]
a.append(str(3))
b = ''.join(a)
print (b)
Since the numbers are stored as ints instead of strings it makes it slightly more difficult as you will need to cast them to strings.
a=[2]
a.append(3)
print("".join(str(x) for x in a))
This will give your desired output. If you want the output to be an int then you can just cast it back.

Making multiple output lists into one list (python)

I have this generator
def keys():
objects = [{'1':True,'2':True,'3':False,'4':False,'5':True,'6':True}]
rng = range(len(objects))
clean = int(''.join(map(str, rng)))
for keys, values in objects[clean].iteritems():
if values == True:
yield keys
and then i want to get all the generator values, which I do using for loop
for i in keys():
i= i.split()
print i
and the output is :
['1']
['2']
['5']
['6']
is there a way I can add them to a single list?
like [['1'],['2'],['5'],['6']] or most preferably ['1','2','5','6'].
Would greatly appreciate your help. Thanks
You can just convert it to a list directly, as list takes an iterable;
out = list(keys())
Or if you want to, you could use a list comprehension;
out = [key for key in keys()]
This would make it easier to filter out certain items from the generator using the [for x in y if z] syntax.
Both output;
>>> print(out)
['2', '6', '1', '5']
Like this?:
my_list = []
for i in keys():
my_list.append(i.split())
print my_list
It would be a list comprehension like this if you want it as similar as possible to your original answer:
list = [key.split() for key in keys()]
print(list)

Convert a string to a list and convert the elements to integers

So I have a string and I want to convert it to a list
input:
"123|456|890|60"
output:
[123,456,890,60]
Another example, input:
"123"
output:
[123]
Here is what I did until now.
A=input()
n=len(A)
i=0
z=0
K=""
Y=[0]*n
while(i<n):
if(A[i]=="|"):
Y[z]=int(Y[z])
j=+1
K=""
else:
Y[z]=K+A[i]
i+=1
print(Y)
Thanks for editing in your attempt. Splitting a string and converting a string to an integer are very common tasks, and Python has built in tools to achieve them.
str.split splits a string into a list by a given delimiter.
int can convert a string to an integer. You can use map to apply a function to all elements of a list.
>>> map(int, "123|456|890|60".split('|'))
[123, 456, 890, 60]
Using list comprehension
Code:
[int(a) for a in "123|456|890|60".split("|")]
Output:
[123, 456, 890, 60]
Notes:
Split creates a list of strings here where the current strings are split at |
We are looping over the list and converting the strings into int
Here's a similar approach, using regular expressions instead:
import re
def convert_string(s):
return map(int, re.findall(r'[0-9]+', s))
Or using a list comprehension:
import re
def convert_string(s):
return [int(num) for num in re.findall(r'[0-9]+', s)]
This is a more general approach and will work for any character (in this case '|') that separates the numbers in the input string.

Split keys (12-13-14) of a dict and find lowest number

What loop can I build to split the following two keys from dictionary "x", and assign the lowest value to a string?
x.keys()
['12-13-14', '1-2-3']
The output should be the following string:
['12', '1']
I know I probably need .split("-"), but I don't know how to write the loop to do this.
No loop needed; just use a list comprehension.
>>> keys = ['12-13-14', '1-2-3']
>>> [str(min(int(x) for x in key.split('-'))) for key in keys]
['12', '1']
What this does: for each key in keys, it splits the key by - using split('-'), just as you thought, and converts those to int (because 2 < 12, but '2' > '12'), finds the min of those, and convert back to str.
Or even shorter (and much more concise), as suggested by #poke:
>>> [min(key.split('-'), key=int) for key in keys]
This does not convert to int and back to str, but instead uses int as the key function by which to determine the minimum.

Categories