簡體   English   中英

如何對字符串列表進行排序?

[英]How to sort a list of strings?

在 Python 中創建按字母順序排序的列表的最佳方法是什么?

基本答案:

mylist = ["b", "C", "A"]
mylist.sort()

這會修改您的原始列表(即就地排序)。 要獲得列表的排序副本,而不更改原始列表,請使用sorted()函數:

for x in sorted(mylist):
    print x

但是,上面的示例有點幼稚,因為它們沒有考慮語言環境,並執行區分大小寫的排序。 您可以利用可選參數key來指定自定義排序順序(使用cmp的替代方案是一個已棄用的解決方案,因為它必須被多次評估 - 每個元素只計算一次key )。

因此,要根據當前語言環境進行排序,並考慮特定於語言的規則( cmp_to_key是來自 functools 的輔助函數):

sorted(mylist, key=cmp_to_key(locale.strcoll))

最后,如果需要,您可以指定用於排序的自定義語言環境

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
  key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']

最后一點:您將看到使用lower()方法的不區分大小寫排序的示例 - 這些示例是不正確的,因為它們僅適用於 ASCII 字符子集。 對於任何非英語數據,這兩個都是錯誤的:

# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)

還值得注意的是sorted()函數:

for x in sorted(list):
    print x

這將返回一個新的、排序的列表版本,而不更改原始列表。

list.sort()

真的就是這么簡單:)

對字符串進行排序的正確方法是:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

前面的mylist.sort(key=lambda x: x.lower())示例適用於mylist.sort(key=lambda x: x.lower()) ASCII 上下文。

請在 Python3 中使用 sorted() 函數

items = ["love", "like", "play", "cool", "my"]
sorted(items2)

但這如何處理特定於語言的排序規則? 它是否考慮了語言環境?

不, list.sort()是一個通用的排序函數。 如果要根據 Unicode 規則進行排序,則必須定義自定義排序鍵函數。 你可以嘗試使用pyuca模塊,但我不知道它有多完整。

老問題,但如果您想在不設置locale.LC_ALL情況下進行區域設置感知排序,您可以按照此答案的建議使用PyICU 庫

import icu # PyICU

def sorted_strings(strings, locale=None):
    if locale is None:
       return sorted(strings)
    collator = icu.Collator.createInstance(icu.Locale(locale))
    return sorted(strings, key=collator.getSortKey)

然后調用例如:

new_list = sorted_strings(list_of_strings, "de_DE.utf8")

這對我有用,無需安裝任何語言環境或更改其他系統設置。

(這已經在上面的評論中提出,但我想更加突出它,因為我自己一開始就錯過了。)

假設s = "ZWzaAd"

要在字符串上方排序,簡單的解決方案將低於一個。

print ''.join(sorted(s))

或者也許:

names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))
l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)

結果

['abc', 'ba', 'cd', 'dc', 'xy']

很簡單: https : //trinket.io/library/trinkets/5db81676e4

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

score = score.split(',') for x in sorted(scores): print(x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM