Python|对给定字符串列表中的所有子列表进行排序
给定一个列表列表,任务是对给定字符串列表中的每个子列表进行排序。
例子:
Input:
lst = [['Machine', 'London', 'Canada', 'France'],
['Spain', 'Munich'],
['Australia', 'Mandi']]
Output:
flist = [['Canada', 'France', 'London', 'Machine'],
['Munich', 'Spain'],
['Australia', 'Mandi']]
有多种方法可以按字母顺序对每个列表进行排序。
方法#1:使用地图
# Python code to sort all sublists
# in given list of strings
# List initialization
Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'],
['Spain', 'Munich'],
['Australia', 'Mandi']]
# Using map for sorting
Output = list(map(sorted, Input))
# Printing output
print(Output)
输出:
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
方法 #2:使用 lambda 并排序
# Python code to sort all sublists
# in given list of strings
# List initialization
Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'],
['Spain', 'Munich'],
['Australia', 'Mandi']]
# using lambda and sorted
Output = [sorted(x, key = lambda x:x[0]) for x in Input]
# Printing output
print(Output)
输出:
[[‘Canada’, ‘France’, ‘London’, ‘Lanka’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
方法#3:使用迭代和排序
# Python code to sort all sublists
# in given list of strings
# List initialization
Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'],
['Spain', 'Munich'],
['Australia', 'Mandi']]
# sorting sublist
for sublist in Input:
sublist.sort()
# Printing output
print(Input)
输出:
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]