【问题标题】:Sort a string in the list alphabetacaly按字母顺序对列表中的字符串进行排序
【发布时间】:2023-01-25 03:26:49
【问题描述】:

我有以下列表:

strs = ["tea","tea","tan","ate","nat","bat"]

我想将该列表中的字符串排序为:

strs = ["aet","aet","ant","aet","ant","abt"]

我该怎么做?

谢谢

【问题讨论】:

    标签: python arrays list sorting


    【解决方案1】:

    尝试如下:

    >>> list(''.join(sorted(s)) for s in strs)
    ['aet', 'aet', 'ant', 'aet', 'ant', 'abt']
    
    # Or
    
    >>> list(map(''.join, map(sorted, strs)))
    ['aet', 'aet', 'ant', 'aet', 'ant', 'abt']
    

    【讨论】:

      【解决方案2】:
      out = []
      for val in strs:
          out.append("".join(sorted(list(val))))
      print(out)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-23
        • 2021-07-05
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 2015-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多