【问题标题】:How can I sort a specific range of elements in a list?如何对列表中特定范围的元素进行排序?
【发布时间】:2011-10-18 00:19:26
【问题描述】:

假设我有一个列表,

lst = [5, 3, 5, 1, 4, 7]

我想让它从第二个元素 3 到最后排序。

我想我可以这样做:

lst[1:].sort()

但是,这行不通。

我该怎么做?

【问题讨论】:

    标签: python algorithm list sorting range


    【解决方案1】:

    最好在切片内进行。

    >>> lst = [5, 3, 5, 1, 4, 7]
    >>> lst[1:]=sorted(lst[1:])
    >>> lst
    [5, 1, 3, 4, 5, 7]
    

    【讨论】:

      【解决方案2】:
      so = lambda x, index: x[:index]+sorted(x[index:])
      

      所以叫它so(lst, 1)

      In [2]: x = [5, 3, 5, 1, 4, 7]
      In [3]: so(lst, 1)
      Out[4]: [5, 1, 3, 4, 5, 7]
      

      【讨论】:

        【解决方案3】:
        lst = [5, 3, 5, 1, 4, 7]
        lst[1:] = sorted(lst[1:])
        print(lst) # prints [5, 1, 3, 4, 5, 7]
        

        【讨论】:

          【解决方案4】:

          您可以使用以下代码:

          lst = [5, 3, 5, 1, 4, 7]
          
          searchValue = 3
          
          def get_sorted(lVals, searchVal=None, startIndex=None):
              if startIndex and startIndex < len(lVals):
                  return lVals[:startIndex] + sorted(lVals[startIndex:])         
              elif searchVal and searchVal in lVals:
                  valueIndex = lst.index(searchValue)
                  return lVals[:valueIndex] + sorted(lVals[valueIndex:])
              return sorted(lVals)
          

          【讨论】:

          • 有这么糟糕吗?是否抛出异常?它没有达到预期的效果吗?
          • 很难猜测 OP 可能意味着的所有内容,而不是像你应该的那样要求 OP 更清楚:)
          【解决方案5】:
          lst = lst[0:1] + sorted(lst[1:])
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-07-04
            • 1970-01-01
            • 1970-01-01
            • 2019-02-07
            • 1970-01-01
            • 2015-06-16
            相关资源
            最近更新 更多