小编use*_*918的帖子

对深度嵌套的元组进行排序

我有一个嵌套元组列表,如下所示:

l = [('apple', ['gala','fuji', 'macintosh']),
('pear', ['seckel','anjou','bosc'])]
Run Code Online (Sandbox Code Playgroud)

我喜欢按字母顺序排序元组的第二项,以便它看起来像:

l2 = [('apple', ['fuji','gala', 'macintosh']),
('pear', ['anjou','bosc','seckel'])]
Run Code Online (Sandbox Code Playgroud)

我知道我可以申请sorted(l)它,但我对Python很新,我遇到迭代问题.我怎样才能做到这一点?

python iteration tuples python-3.x

3
推荐指数
2
解决办法
205
查看次数

通过float元素对元组进行排序

我试图通过数字的值对此元组进行排序,以便按降序重新排列:

l =[('orange', '3.2'), ('apple', '30.2'), ('pear', '4.5')]
Run Code Online (Sandbox Code Playgroud)

如:

l2 =[('apple', '30.2'), ('pear', '4.5'), ('orange', '3.2')]
Run Code Online (Sandbox Code Playgroud)

我试图用它来排序它:

l2 = ((k,sorted(l2), key=lambda x: float(x[1]), reverse=True)))
       [value for pair in l2 for value in pair]
Run Code Online (Sandbox Code Playgroud)

但我收到错误消息:

TypeError: float() argument must be a string or a number, not 'tuple'
Run Code Online (Sandbox Code Playgroud)

我如何纠正这一点,以便我可以表明我想按每对中的数字排序?Python语法仍然让我很困惑,因为我对它很新.任何帮助,将不胜感激.

python sorting tuples python-3.x

2
推荐指数
1
解决办法
2515
查看次数

标签 统计

python ×2

python-3.x ×2

tuples ×2

iteration ×1

sorting ×1