我希望按字符串(行)的长度对单词进行排序,然后在列表中按每行中单词的数量对它们进行排序。
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
答案 0 :(得分:1)
如果我已经正确理解了你想要完成的任务,那就可以做到:
pin = 0
#...
this_pair = idx1*5 + idx2
pin = pin * 100 + this_pair
print(pin)
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)