views:

171

answers:

3

I have: L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8'] this is a list of strings, right? I need to make it a list of integers as follows: L2 = [11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]

finally I will sort it like below: L3 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] by L2.sort()

please let me know how I can get to L3 from L1

+5  A: 
>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8'] 
>>> L1 = [int(x) for x in L1]
>>> L1
[11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
>>> L1.sort()
>>> L1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> L3 = L1
N 1.1
+18  A: 

You could do it in one step like this:

L3 = sorted(map(int, L1))

In more detail, here are the steps:

>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> L1
['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> map(int, L1)
[11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
>>> sorted(_)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>>
Greg Hewgill
I didn't know you can use the underscore like that. Is that interpreter specific? +1
Xavier Ho
@Xavier, that's a little convenience thing within the interactive interpreter only.
Mike Graham
Yes `_` only does work in the interpreter this way. The only way I know of to "access" `_` within a script is inside a list comprehension `locals()['_[1]'].__self__` will return the list that is being constructed.
Ivo Wetzel
+4  A: 
L3 = sorted(int(x) for x in L1)
Chris AtLee