1

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
1
  • It's hard to tell what you're asking. Maybe provide an example of expected output and some code that you have tried? Commented Sep 10, 2010 at 6:01

3 Answers 3

3

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))
Sign up to request clarification or add additional context in comments.

2 Comments

+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.
+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.
2

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.

Comments

1

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.

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.