基于字符串列表的元组顺序列表

时间:2014-07-02 22:08:09

标签: python

我有两个列表orderdataorder应该是data中元组列表的顺序。

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

我似乎无法为此开发出一个好的算法。我得到的最近的是:

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

只按字母顺序排列所有内容。

关于如何做到这一点的好方法?

3 个答案:

答案 0 :(得分:1)

如何使用字典作为中间人?

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

答案 1 :(得分:1)

您可以将order变成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)]

答案 2 :(得分:1)

您只需要按顺序对数据元组的第一个元素进行排序:

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

您也可以就地排序:

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

如果您有重复的元素,这也会有效:

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