Python|按字符串的一部分对给定的字符串列表进行排序
给定一个字符串列表,任务是按由某个字符分隔的字符串部分对列表进行排序。在这种情况下,我们正在考虑将字符串用空格分隔,这意味着它必须按每个字符串的第二部分进行排序。
下面给出了一些解决给定任务的方法。
方法#1:使用排序
# Python code to demonstrate to sort list
# containing string by part of string
# Initialising list
ini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
# printing initial list
print ("initial list", str(ini_list))
# code to sort list
ini_list.sort(key = lambda x: x.split()[1])
# printing result
print ("result", str(ini_list))
输出:
initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
方法#2:使用排序
# Python code to demonstrate to sort list
# containing string by part of string
# Initialising list
ini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
# printing initial list
print ("initial list", str(ini_list))
# code to sort list
res = sorted(ini_list, key = lambda x: x.split()[1])
# printing result
print ("result", res)
输出:
initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']