简体   繁体   English

如何根据索引零 [0] 处的元组元素对 python 列表进行排序

[英]How to sort python list based on its element that is a tuple at index zero [0]

I have a python list right here我这里有一个 python 列表

my_list = [("ww","hello"),("www","world"),("w","sardines")]

So I wanted to sort this list based on the length value of the first index of the tuple element which is as you can see there is the letter "w" .所以我想根据元组元素的第一个索引的长度值对这个列表进行排序,正如你所看到的,有字母"w" To be more specific the output should be like this更具体地说,输出应该是这样的

my_list = [("w","sardines"),("ww","hello"),("www","world")]

I've searched many sorting techniques for this but I find those with for example a string element only.我为此搜索了许多排序技术,但我发现那些只有字符串元素。 I was thinking of using a sorting algorithm for this like bubble sort, merge sort, insertion or any other sorting algorithm... but I think I am lost in that part and also I think that there is a better way to do this without even using a sorting algorithm.我正在考虑为此使用排序算法,例如冒泡排序、合并排序、插入或任何其他排序算法......使用排序算法。 I feel like there's a simpler way like just calling a .sort() function.我觉得有一种更简单的方法,比如调用.sort()函数。

Thank you so much for your help!非常感谢你的帮助! Glad to ask questions here in this great community!很高兴在这个伟大的社区在这里提问! Thank you!谢谢!

Try this:尝试这个:

my_list = [("ww","hello"),("www","world"),("w","sardines")]

def take_el(elem):
    return len(elem[0])

sorted(my_list, key=take_el)

or with lambda或使用 lambda

sorted(my_list, key = lambda x: len(x[0]))

Use this simple technique to sort on the basis of 1st element in tuple:使用这种简单的技术根据元组中的第一个元素进行排序:

sorted(my_list, key=lambda x: len(x[0]))

Change x[0] to x[1] to sort the list using the length of 2nd tuple element and so on..x[0]更改为x[1]以使用第二个元组元素的长度对列表进行排序,依此类推。

my_list = [("ww","hello"),("www","world"),("w","sardines")]
listOrder = []
newList = []
for i in my_list:
    listOrder.append(int(len(i[0])))
listOrder.sort()
for i in listOrder:
    for j in my_list:
        if i == len(j[0]):
            newList.append(j)

print(newList)

This will also help.这也会有所帮助。

use sorted where x is the tuple and x[n] is the slice使用 sorted 其中 x 是元组,x[n] 是切片

my_list = [("ww","hello"),("www","world"),("w","sardines")]

result = sorted(my_list, key = lambda x: x[0])
print(result)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM