【问题标题】:I want to arrange the list of strings with a certain condition我想安排具有特定条件的字符串列表
【发布时间】:2019-10-03 14:04:41
【问题描述】:

我想按字母顺序排列字符串列表,但条件是以 x 开头的字符串排在第一位。例如,输入为 list=['apple','pear','xanadu','stop']。

我确定您需要在排序函数中添加一些条件,但我不确定该放什么。

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']。顺便说一句,我删除了“停止”。

【问题讨论】:

    标签: python-3.x string list


    【解决方案1】:

    使用将确定元素顺序的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 的元组。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多