[英]How to sort a list nested inside another list?
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)
for this given input: 对于此给定的输入:
5654 3456 7215 7612 5463
I get the list as: 我得到的列表为:
[[5, 6, 5, 4], [3, 4, 5, 6], [7, 2, 1, 5], [7, 6, 1, 2], [5, 4, 6, 3]]
I want the output to be like: 我希望输出如下所示:
[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]
How to get this output? 如何获得此输出?
Try a list comprehension where you map your strings to integers and then sort them using sorted
尝试使用列表理解 ,将字符串映射为整数,然后使用sorted
对它们进行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]]
You can use map for this: 您可以为此使用地图:
n_list = list(map(sorted, n_list))
or directly: 或直接:
n_list = list(map(lambda n:sorted(map(int,n)), input().split())
inp = '5654 3456 7215 7612 5463' # user input
res= [] # list to store the final output
# iterating over each number which is divided into a list via inp.split()
for i in inp.split():
# keeping internal list which will keep the each digit in int format
tmp=[]
for j in i: # iterating over the number eg 5654
# converting each digit to int and adding it to temp list
tmp.append(int(j))
# sorting internal list and appending it to final result list
res.append(sorted(tmp))
print(res) # printing final list
output 产量
[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.