用lis中的单词排序字符串

2024-06-23 19:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按字串(行)的长度对字串排序,然后按每行的字数在列表中排序。你知道吗

list_of_words = ['hoop t','hot op','tho op','ho op t','phot o']

所以输出是:

hoot t
phot o
hot op
tho op
ho op t

Tags: of列表排序listwordsophot字数
1条回答
网友
1楼 · 发布于 2024-06-23 19:27:58

如果我正确地理解了你想要实现的目标,这就可以做到:

list_of_words = ['hoop t','hot op','tho op','ho op t','phot o']

# first sort the words in each string by their length, from longest to shortest
for i, words in enumerate(list_of_words):
    list_of_words[i] = sorted(words.split(), key=len, reverse=True)

# second sort the list by how many words there are in each sublist
list_of_words.sort(key=lambda words: len(words))  # sorts list in-place

# third, join the words in each string back together into a single string
for i, words in enumerate(list_of_words):
    list_of_words[i] = ' '.join(words)

# show results
print(list_of_words)
['hoop t', 'hot op', 'tho op', 'phot o', 'ho op t']

相关问题 更多 >

    热门问题