【问题标题】:For loop - Sorting each character alphabetically within a list of wordsFor 循环 - 在单词列表中按字母顺序对每个字符进行排序
【发布时间】:2011-09-14 12:32:36
【问题描述】:

我有一个单词列表,我想在列表中按字符排序:

['alumni', 'orphan', 'binge', 'peanut', 'necktie']

我想按字母顺序对它们进行排序,以便它们最终成为以下列表:

['ailmnu', 'ahnopr', 'begin', 'aenptu', 'ceeiknt']

到目前为止我的代码一直很尴尬:

for i in range(len(splitfoo)):
    splitedfootmp = sorted(splitfoo[i])

将单词拆分为如下字符:['a', 'i', 'l', 'm', 'n', 'u'] 但我不知道如何将其转回['ailmnu']

有没有办法做到这一点而不经历所有的麻烦? 提前致谢!

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    把你的事情做好:

    items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
    sorted_items = ["".join(sorted(item)) for item in items]
    

    我在这里使用list comprehension,这是制作像这样的小型sn-ps 的好方法。如果需要,您可以将其扩展为:

    items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
    sorted_items = []
    for item in items:
        sorted_items.append("".join(sorted(item)))
    

    但显然,在这种情况下,列表理解是一种更好的(并且比上述或使用map() 更快)的解决方案。

    还值得注意的是,使用这样的 for 循环并不是很 Pythonic。比较:

    for i in range(len(splitfoo)):
        splitedfootmp = sorted(splitfoo[i])
    
    for item in splitfoo:
        splitedfootmp = sorted(item)
    

    他们都做同样的事情,但后者更清晰和pythonic。

    【讨论】:

      【解决方案2】:
      In [1]: ''.join(['a', 'i', 'l', 'm', 'n', 'u'])
      Out[1]: 'ailmnu'
      

      这是一个完整的程序:

      In [2]: l = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
      
      In [3]: map(lambda w: ''.join(sorted(w)), l)
      Out[3]: ['ailmnu', 'ahnopr', 'begin', 'aenptu', 'ceeiknt']
      

      【讨论】:

        【解决方案3】:

        string.join()

        您还可以使用map() 函数来简化您的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-23
          • 1970-01-01
          • 2023-01-25
          • 1970-01-01
          相关资源
          最近更新 更多