1

I have the following:

line  = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777',,'aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']

Is there away I can sort by (Bob,Larry,Steve) then by (1111,2222)?

so...

for i in line:
    i = i.split(' ')
    pos1 = i[0]
    pos2 = i[1]
    pos3 = i[2]
    pos4 = i[3]

So I need to sort by pos3 and then by pos2.

Desired output would be:

'aaaa, 1111, BOB, 7777'
'aaaa, 1111, BOB, 8888'
'BBBB, 2222, BOB, 7777'
'aaaa, 1111, larry, 7777'
'aaaa, 1111, Steve, 8888'

1 Answer 1

6

Leave the splitting to a key function:

sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1])

This returns the strings in line in lexicographically sorted order, case-insensitive. The [2:0:-1] slice returns the third and second columns in reverse order.

Demo:

>>> line  = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777','aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']
>>> from pprint import pprint
>>> pprint(sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1]))
['aaaa, 1111, BOB, 7777',
 'aaaa, 1111, BOB, 8888',
 'BBBB, 2222, BOB, 7777',
 'aaaa, 1111, larry, 7777',
 'aaaa, 1111, Steve, 8888']

If your 'lines' are not as neatly comma + space separated, you may need to strip whitespace too.

Sign up to request clarification or add additional context in comments.

4 Comments

That doesn't seem to give me the desired output I added above
@Dumbkid_trying: Made it case-insensitive, fixed the incorrect slice (I missed how you numbered your columns).
perfect, how is this )[2:0:-1])) splitting it. Just trying to get a better understanding
@Dumbkid_trying: It is not. .split(', ') does the splitting, returning a list. The [2:0:-1] takes a slice from that list, in reverse order (the last element :-1 defines the stride, negative strides count backwards). It starts at index 2, then counts down to index 0 (which is not included). So in the end a new list is returned containing index 2 and index 1, in that order.

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.