我想按字母顺序排列字符串列表,但条件是以x开头的字符串优先。例如,输入为list = ['apple','pear','xanadu','stop']。
我确定您需要在sort函数上添加一些条件,但是我不确定该放置什么。
list2=[]
string=input("Enter a string:")
list2.append(string)
while string!="stop":
string=input("Enter a string:")
list2.append(string)
list2.remove("stop")
print("Your list is:",list2)
print("Sorted list:",sorted(list2))
我希望输出为list = ['xanadu','apple','pear']。我删除了“停止”顺便说一句。
答案 0 :(得分:0)
使用key
函数将确定元素的顺序:
>>> sorted(['apple','pear','xanadu','stop'], key=lambda val: (0, val) if val.startswith('x') else (1, val))
['xanadu', 'apple', 'pear', 'stop']
lambda的含义如下:
lambda val:\ # determine the ordering of the element `val`
(0, val)\ # make the algorithm compare tuples!
if val.startswith('x')\
else (1, val) # use default alphabetical ordering otherwise
由于我们现在正在比较元组(但对实际值进行排序),因此第一个元素为零的元组将始终大于第一个元素为1的元组。