Python For loop-在单词列表中按字母顺序对每个字符进行排序
我有一个单词列表,我想在列表中按字符排序:Python For loop-在单词列表中按字母顺序对每个字符进行排序,python,for-loop,Python,For Loop,我有一个单词列表,我想在列表中按字符排序: ['alumni', 'orphan', 'binge', 'peanut', 'necktie'] 我想按字母顺序对这些文件进行排序,以便它们最终成为以下列表: ['ailmnu', 'ahnopr', 'begin', 'aenptu', 'ceeiknt'] 到目前为止,我的代码一直令人尴尬: for i in range(len(splitfoo)): splitedfootmp = sorted(splitfoo[i]) 将单词
['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']
有没有办法不费吹灰之力就能做到这一点?
提前谢谢
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']
下面是一个完整的程序:
In [2]: l = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
In [3]: map(lambda w: ''.join(sorted(w)), l)
Out[3]: ['ailmnu', 'ahnopr', 'begin', 'aenptu', 'ceeiknt']
为了把你的事情做好:
items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
sorted_items = ["".join(sorted(item)) for item in items]
在这里,我使用了一个,这是一个很好的方法来制作这样的小片段。如果需要,可以将其展开为:
items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
sorted_items = []
for item in items:
sorted_items.append("".join(sorted(item)))
但是很明显,在这种情况下,列表理解是一种更好(并且比上面提到的或使用map()
更快)的解决方案
同样值得一提的是,使用这样的for循环并不是很符合Python。比较:
for i in range(len(splitfoo)):
splitedfootmp = sorted(splitfoo[i])
for item in splitfoo:
splitedfootmp = sorted(item)
它们都做同样的事情,但后者更清晰,更具蟒蛇式。要把整个事情做好:
items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
sorted_items = ["".join(sorted(item)) for item in items]
在这里,我使用了一个,这是一个很好的方法来制作这样的小片段。如果需要,可以将其展开为:
items = ['alumni', 'orphan', 'binge', 'peanut', 'necktie']
sorted_items = []
for item in items:
sorted_items.append("".join(sorted(item)))
但是很明显,在这种情况下,列表理解是一种更好(并且比上面提到的或使用map()
更快)的解决方案
同样值得一提的是,使用这样的for循环并不是很符合Python。比较:
for i in range(len(splitfoo)):
splitedfootmp = sorted(splitfoo[i])
for item in splitfoo:
splitedfootmp = sorted(item)
它们都做同样的事情,但后者更清晰,更像Python。看看string.join()
您还可以使用map()
函数简化代码。查看string.join()
您还可以使用map()
函数简化代码