如何对嵌套在另一个列表中的列表进行排序? [英] How to sort a list nested inside another list?

查看:69
本文介绍了如何对嵌套在另一个列表中的列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有嵌套在外部列表中的列表.我想对内部列表中的元素进行排序,而不更改外部列表中元素(在本例中为列表)的位置.怎么做?

I have lists nested inside an outer list. I want to sort the elements in inner lists without changing the position of the elements(lists in this case) in outer list. How to do it?

我得到了空格分隔的用户输入,然后我将其转换为嵌套列表,其中每个内部列表都包含彼此分隔的数字的数字.我想要的只是以排序的形式获取内部列表

I am getting space separated user input which I later convert to nested lists where each inner list contain the digits of the number separated from each other. All I want is to get the inner lists in sorted form

num = list(map(str, input().split()))
n_list = []
for i in range(len(num)):
    num_in_num = [int(j) for j in num[i]]
    n_list.append(num_in_num)
print(n_list)

对于这个给定的输入:

5654 3456 7215 7612 5463

我得到的列表如下:

[[5, 6, 5, 4], [3, 4, 5, 6], [7, 2, 1, 5], [7, 6, 1, 2], [5, 4, 6, 3]]

我希望输出如下:

[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]

如何得到这个输出?

推荐答案

尝试 list comprehension 将字符串映射到整数,然后使用 sorted

Try a list comprehension where you map your strings to integers and then sort them using sorted

num = ['5654', '3456', '7215', '7612', '5463']
answer = [sorted(map(int, i)) for i in num]
# [[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]

这篇关于如何对嵌套在另一个列表中的列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆