简体   繁体   中英

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?

How about using a dictionary as an intermediary?

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

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)]

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>')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM