簡體   English   中英

在 Python 的 List 中找到五個最長的單詞並按字母順序排列

[英]Find five longest words in a List in Python and order them in alphabetical order

這是我第一次使用 Python 進行 Uni 作業,我面臨的任務是:在整個文本中提取五個最長的單詞,用這些項目創建一個列表並按字母順序排列。 在屏幕上打印出這些結果(例如,'此文本中按字母順序排列的五個最長單詞是:“word1”、“word2”、“word3”、“word4”、“word5”')

所以,到目前為止我創建的代碼是:

print(longest_string)

second_longest_string = sorted(word_list, key=len)[-2]
print(second_longest_string)

third_longest_string = sorted(word_list, key=len)[-3]
print(third_longest_string)

fourth_longest_string = sorted(word_list, key=len)[-4]
print(fourth_longest_string)

fifth_longest_string = sorted(list_1, key=len)[-5]
print(fifth_longest_string) ```

I thought I could start by this and then proceed to the alphabetical order, but it looks like this code generates a different output every time, because inside the list there are many strings that have the same number of words. 

Any idea how I can proceed?

Thank you.

這將根據長度對單詞列表進行排序,然后得到 5 個最長的單詞,然后根據字母順序對它們進行排序

sorted_words = sorted(sorted(word_list, key=len)[-5:])

方法之一:

data = """
It's the first time I am working with Python for a Uni assignment and am facing a difficulty regarding a task that says: Extract five longest words in the entire text, create a List with those items and order them alphabetically. Print out these results on the screen"""
import re
# Remove all characters except words, space and ' from data
data = re.sub("[^a-zA-Z ']+", "", data)
words = sorted(data.split(), key=len)
print (f'Five longest words in this text ordered alphabetically are: {",".join(sorted(words[-5:]))}')

Output:

Five longest words in this text ordered alphabetically are: alphabetically,assignment,difficulty,regarding,results
import string

Text = """It's the first time I am, working with Python for a Uni assignment and I am facing a difficulty regarding a task that says: Extract five longest words in the entire text, create a List with those items and order them alphabetically."""
EditText = ''.join([x for x in Text if x in string.ascii_letters + '\'- ']) #get only words from string Text
Words = EditText.split(" ") # make a list with all worlds
SortedWords = sorted(sorted(Words, key=len)[-5:])

print(f'Five longest words in this text ordered alphabetically are: {", ".join(SortedWords)}.')

Output:

Five longest words in this text ordered alphabetically are: alphabetically, assignment, difficulty, longest, regarding.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM