[英]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.