简体   繁体   English

如何按元组的长度对元组列表进行排序

[英]How to sort a list of tuples by the length of the tuple

I have a list, which has a bunch of tuples of different sizes inside.我有一个列表,里面有一堆不同大小的元组。 Each Tuple contains a certain number of objects.每个元组包含一定数量的对象。 I want to sort the list so the tuples with 1 object are all before tuples with 2 objects etc. I know tuples have a built in length but I dont know how to use it with the sort method in python.我想对列表进行排序,以便具有 1 个对象的元组都在具有 2 个对象等的元组之前。我知道元组具有内置长度,但我不知道如何将它与 Python 中的 sort 方法一起使用。 Thank you!谢谢!

Use this:用这个:

print(sorted(list_of_tuples,key=len))

Or:或者:

list_of_tuples.sort(key=len)
print(list_of_tuples)

Both reproduce the expected result.两者都重现了预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据元组中的变量对元组列表进行排序 - How to sort list of tuples based on variable in tuple 如何按第二个元组元素对元组列表进行排序? - How to sort a list of tuples, by the second tuple element? 如何根据另一个列表中元组元素的顺序对元组列表进行排序? - How to sort a list of tuples according to the order of a tuple element in another list? 如何根据元组列表中的值对元组进行排序 - How to sort a tuple based on a value within the list of tuples 如何按给定索引处的元素对列表/元组的列表/元组进行排序? - How to sort a list/tuple of lists/tuples by the element at a given index? 如何使用元组的两个元素对元组列表进行排序? - How to sort list of tuples using both elements of tuple? 如何对元组列表进行排序,但一个特定的元组是第一个? - How to sort a list of tuples but with one specific tuple being the first? 根据下一个元组的长度加入列表中的元组 - Join tuples in list based on length of next tuple 按Python 3中的特定元组元素对元组列表进行排序 - Sort list of tuples by specific tuple element in Python 3 如何按每个元组中的第一个元素对元组列表进行排序,并选择每个组中最后一个元素最大的元组 - How to sort a list of tuples by the first element in each tuple, and pick the tuple with the largest last element in each group
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM