Buddy Lindsey
Buddy Lindsey

Reputation: 3630

Order list of tuples based on a list of strings

I have two lists order and data. order is meant to be the order in which the list of tuple's in data should be.

# two lists
order = ['name', 'email', 'phone', 'zip']
data = [(email, <object>), ('zip', <object>), ('name', <object>), ('phone', <object>)]

# what the result should be
[('name', <object>), ('email', <object>), ('phone', <object>), ('zip', <object>)]

I can't seem to develop a good algorithm for this. Closest I have gotten is:

result = [x for (x, y) in sorted(zip(data, order), key=lambda pair: pair[0])]

Which just orders everything in alphabetical order.

Any thoughts on a good way to do this?

Upvotes: 1

Views: 57

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You just need to sort on the first element of your data tuples based on its index in order:

order = ['name', 'email', 'phone', 'zip']
data = [("email", "<object>"), ('zip', "<object>"), ('name', "<object>"), ('phone', "<object>")]

print sorted(data,key=lambda x:order.index(x[0]))
[('name', '<object>'), ('email', '<object>'), ('phone', '<object>'), ('zip', '<object>')]

You can sort in-place also:

data.sort(key=lambda x:order.index(x[0]))
print data
[('name', '<object>'), ('email', '<object>'), ('phone', '<object>'), ('zip', '<object>')]

This will also work if you have repeated elements:

data = [("email", "<object>"),("email", "<object>"), ('zip', "<object>"), ('name', "<object>"), ('phone', "<object>"),('name', "<object>")]
data.sort(key=lambda x:order.index(x[0]))
print data
[('name', '<object>'), ('name', '<object>'), ('email', '<object>'), ('email', '<object>'), ('phone', '<object>'), ('zip', '<object>')]

Upvotes: 1

C.B.
C.B.

Reputation: 8326

You could turn order into a dict

>>> data = [('email', None), ('zip', None), ('name', None), ('phone', None)]
>>> order = {'name':0, 'email':1, 'phone':2, 'zip':3}
>>> sorted(data, key=lambda item : order[item[0]])
[('name', None), ('email', None), ('phone', None), ('zip', None)]

Upvotes: 1

s4y
s4y

Reputation: 51705

How about using a dictionary as an intermediary?

index = { t[0]: t for t in data }
result = [index[k] for k in order]

Upvotes: 1

Related Questions