按大小写排序元组中的元组
你好! 我有一个元组,看起来是这样的:
tup = ((3,'Ne'),(7,'yo'),(1,'Hey'),(3,'ne'),(7,'Yo'),(1,'hey'))
我用这个来按字母顺序排序:
sorted(tup, key=lambda tup: tup[1])
但问题是,它输出的是这个:
>>> print tup
>>> ((1,'Hey'),(3,'Ne'),(7,'Yo'),(1,'hey'),(3,'ne'),(7,'yo'))
而我想要输出的是这个(这是我想要的结果):
>>> print tup
>>> ((1,'Hey'),(1,'hey'),(3,'Ne'),(3,'ne'),(7,'Yo'),(7,'yo'))
我在网上查了一下,发现可以用 list
对象来做到这一点,但在元组上却不行。
如果能给出 tuple
的解决方案,我会非常感激。 谢谢!
3 个回答
0
sorted(tup, key=lambda x: (x[1].upper(),ord(x[1][0])))
In [2]: tup = ((3,'Ne'),(7,'yo'),(1,'Hey'),(3,'ne'),(7,'Yo'),(1,'hey'))
In [3]: sorted(tup, key=lambda x: (x[1].upper(),ord(x[1][0])))
Out[3]: [(1, 'Hey'), (1, 'hey'), (3, 'Ne'), (3, 'ne'), (7, 'Yo'), (7, 'yo')]
用排序函数来排序,然后用元组字符串第一个字符的ord
值来解决相同的情况。
0
这也可以通过指定一个比较函数来实现,而不是使用一个键。
tup = ((3,'Ne'),(7,'yo'),(1,'Hey'),(3,'ne'),(7,'Yo'),(1,'hey'))
def compare(item1, item2):
if item1[1].lower() < item2[1].lower():
return -1
elif item1[1].lower() > item2[1].lower():
return 1
else:
return -1 if item1[1] < item2[1] else 1
tup = sorted(tup, cmp=compare)
print(tup)
2
我想你是想说
tup = ((3,'Ne'),(7,'yo'),(1,'Hey'),(3,'ne'),(7,'Yo'),(1,'hey'))
而且需要
sorted(tup, key=lambda tup: tup[1].upper())