我有嵌套在外部列表中的列表。我想对内部列表中的元素进行排序而不更改外部列表中元素(在这种情况下为列表)的位置。怎么做?
我得到了空格分隔的用户输入,后来我将其转换为嵌套列表,其中每个内部列表均包含彼此分开的数字。我想要的就是以排序的形式获取内部列表
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]]
如何获得此输出?
答案 0 :(得分:1)
尝试使用list comprehension,将字符串映射为整数,然后使用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]]
答案 1 :(得分:0)
您可以为此使用地图:
n_list = list(map(sorted, n_list))
或直接:
n_list = list(map(lambda n:sorted(map(int,n)), input().split())
答案 2 :(得分:0)
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
输出
[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]