7

如何在区分大小写的情况下高效轻松地对元组列表进行排序?

例如这个:

[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]

排序后应如下所示:

[('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')]

常规的字典排序会将 'A' 放在 'a' 之前并产生:

[('A', 'b'), ('a', 5), ('a', 'a'), ('a', 'c')]
4

5 回答 5

12

您可以使用sort'key参数来定义您希望如何看待每个元素的排序:

def lower_if_possible(x):
    try:
        return x.lower()
    except AttributeError:
        return x

L=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)]

L.sort(key=lambda x: map(lower_if_possible,x))
print(L)

有关如何使用key.

于 2010-03-22T18:30:44.250 回答
2
list_of_tuples.sort(key=lambda t : tuple(s.lower() if isinstance(s,basestring) else s for s in t))
于 2010-03-22T18:32:26.640 回答
0

像这样的东西应该工作:

def sort_ci(items):
    def sort_tuple(tuple):
        return ([lower(x) for x in tuple],) + tuple
    temp = [sort_tuple(tuple) for tuple in items]
    temp.sort()
    return [tuple[1:] for tuple in temp]

换句话说,创建一个新列表,其中每个项目是一个由旧元组组成的元组,前缀为相同的元组,每个项目都小写。然后排序。

如果您的列表很长,这比使用sort的可选比较函数参数要快一些。

于 2010-03-22T18:31:40.957 回答
0

这是一个使用 Python wiki 文章 ( http://wiki.python.org/moin/HowTo/Sorting/ ) 的“按键排序”部分中说明的装饰器思想的解决方案。

# Create a list of new tuples whose first element is lowercase
# version of the original tuple.  I use an extra function to
# handle tuples which contain non-strings.
f = lambda x : x.lower() if type(x)==str else x
deco = [(tuple(f(e) for e in t), t) for t in ex]

# now we can directly sort deco and get the result we want
deco.sort()

# extract the original tuples in the case-insensitive sorted order
out = [t for _,t in deco]
于 2010-03-22T18:33:59.947 回答
0

Paul McGuires 的简化版本可以工作:

list_of_tuples.sort(key=lambda t : tuple(t[0].lower()))

(其中 t[0] 引用您要使用的元组元素,在这种情况下是第一个)

于 2010-06-25T11:57:51.527 回答