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)

の使用方法については、http://wiki.python.org/moin/HowTo/Sortingを参照してください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

Paul McGuires の簡易版は次のように機能します。

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

(ここで t[0] は、使用するタプル要素を参照します。この場合は最初のものです)

于 2010-06-25T11:57:51.527 に答える
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 に答える