views:

108

answers:

5

Hello, i have a list.

name|num|num|num|num
name|num|num|num|num
name|num|num|num|num

How i can sort this list on need me field (2,3,4,5) ? Sorry for my enlish.

Update

Input:

str|10|20
str|1|30

Sort by first field (1,10):

str|1|30
str|10|20

Sort by second field(20,30):

str|10|20
str|1|30
A: 

Input:

str|10|20
str|1|30

Sort by first field (1,10):

str|1|30
str|10|20

Sort by second field(20,30):

str|10|20
str|1|30
Artyom
It's better to edit your question instead of posting answers. can you give an example with an actual python data type? I don't know what 'str|10|20` is.
aaronasterling
+2  A: 

You can sort on a specific key, which tells the sort function how to evaluate the entries to be sorted -- that is, how we decide which of two entries is bigger. In this case, we'll first split up each string by the pipe, using split (for example, "a|b|c".split("|") returns ["a", "b", "c"]) and then grab whichever entry you want.

To sort on the first "num" field:

sorted(lines, key=(lambda line : line.split("|")[1])

where lines is a list of the lines as you mention in the question. To sort on a different field, just change the number in brackets.

Etaoin
A: 

iF field is one:

#name|value

f = open("pre.txt").readlines()
fzas = open("res.txt","w")
zx = {}
for i in xrange(len(f)-1):
    fz =  f[i].strip().split("|")
    zx[fz[0]]=fz[1]
for key in sorted(zx, key = lambda x: int(zx[x]),reverse=True):
    print key, zx[key]
Artyom
A: 

Assuming you start with a list of strings, start by splitting each row into a list:

data = [line.split('|') for line in input]

Then sort by whatever index you want:

sort_index = 1
sorted_data = sorted(data, key=lambda line: int(line[sort_index]))

The Python sorting guide has a lot more information.

Connor M
Etaoin's solution is better.
aaronasterling
+3  A: 

I would use the operator module function "itemgetter" instead of the lambda functions. That is faster and allows multiple levels of sorting.

from operator import itemgetter

data = (line.split('|') for line in input.split('\n')) 
sort_index = 1
sorted(data, key=itemgetter(sort_index))
johnbaum
+1 Optimal solution imo. I'd just store the result of `sorted(...)` in a variable, as it doesn't sort in place (and in-place sorting with `data.sort()` isn't available for generators). But you probably meant that.
jellybean
+1, and agree that the last line would be better as: data.sort(key=..). Also, the poster's original request was for sort_index = (1,2,3,4), which is how one specifies compound keys using Python's 0-based indexing.
Kevin Jacobs