考虑区域设置的元组排序列表(瑞典语排序)

2024-06-16 09:44:42 发布

您现在位置:Python中文网/ 问答频道 /正文

显然,postgresql8.4和ubuntu10.04无法处理瑞典字母W和V的更新排序方式。也就是说,它仍然像这样以相同的字母排序(瑞典式排序的旧定义):

  • 华盛顿州
  • Vb语言
  • 厕所
  • 虚拟磁盘

它应该是(瑞典订单的新定义):

  • Vb语言
  • 虚拟磁盘
  • 华盛顿州
  • 厕所

我需要为我正在构建的Python/Django网站正确订购这个。我尝试过各种方法,使用*values\u list*对从Django QuerySet创建的元组列表进行排序。但由于它是瑞典语,所以字母的顺序必须正确。现在我有一个或另一个方向都不是两个。。在

list_of_tuples = [(u'Wa', 1), (u'Vb',2), (u'Wc',3), (u'Vd',4), (u'Öa',5), (u'äa',6), (u'Åa',7)]

print '########## Ordering One ##############'
ordered_list_one = sorted(list_of_tuples, key=lambda t: tuple(t[0].lower()))
for item in ordered_list_one:
    print item[0]

print '########## Ordering Two ##############'
locale.setlocale(locale.LC_ALL, "sv_SE.utf8")
list_of_names = [u'Wa', u'Vb', u'Wc', u'Vd', u'Öa', u'äa', u'Åa']
ordered_list_two = sorted(list_of_names, cmp=locale.strcoll)
for item in ordered_list_two:
    print item

举例说明:

^{pr2}$

现在,我想要的是这些的组合,这样V/W和å,ä,ö顺序都是正确的。更准确地说。我想订一个来尊重当地环境。然后使用每个元组中的第二个项(objectid),我可以在Django中获取正确的对象。在

我开始怀疑这是否可能?是否可以将PostgreSQL升级到处理排序规则的更新版本,然后在Django中使用原始SQL?在


Tags: ofdjango语言定义排序字母itemlocale
2条回答

这个解决方案很复杂,因为=语言环境.strxfrm工作正常 使用单个列表和字典,但不使用列表列表或 元组列表。在

Py2->Py3的更改:使用语言环境.setlocale(locale.LC\u全部, '') 和key='语言环境.strxfrm'(而不是'cmp=区域设置.strcoll'). 在

list_of_tuples = [('Wa', 1), ('Vb',2), ('Wc',3), ('Vd',4), ('Öa',5), ('äa',6), ('Åa',7)]

def locTupSorter(uLot):
    "Locale-wise list of tuples sorter - works with most European languages"
    import locale
    locale.setlocale(locale.LC_ALL, '') # get current locale

    dicTups = dict(uLot)          # list of tups to unsorted dictionary
    ssList = sorted(dicTups, key=locale.strxfrm)
    sLot = []
    for i in range(len(ssList)):  # builds a sorted list of tups 
        tfLot = ()
        elem = ssList[i]          # creates tuples for list
        tfLot = (elem, dicTups[elem])
        sLot.append(tfLot)        # creates sorted list of tuples
    return(sLot)


print("list_of_tuples=\n", list_of_tuples)
sortedLot = locTupSorter(list_of_tuples)
print("sorted list of tuples=\n",sortedLot)

在Ubuntu-10.04的例子中运行LC_ALL=sv_SE.UTF-8 sort时,它在Vb之前是Wa(“旧方法”),因此Ubuntu似乎不同意“新方法”。 由于PostgreSQL依赖于操作系统来完成这项工作,因此它的行为将与给定相同lc\u collate的操作系统相同。在

debian glibc中实际上有一个与此特定排序问题相关的修补程序: http://sourceware.org/bugzilla/show_bug.cgi?id=9724 但它遭到反对,没有被接受。如果您只需要在您管理的系统上执行此行为,您仍然可以将修补程序的更改应用到/usr/share/i18n/locales/sv峎SE,并通过运行locale-gen sv_SE.UTF-8来重新构建seu-sv语言环境。或者更好的是,创建您自己的源于它的替代语言环境,以避免弄乱原始语言环境。在

相关问题 更多 >