簡體   English   中英

如何根據字母順序對列表中的項目進行排序和刪除?

[英]How to sort and remove items from list base on alphabetical?

我的老師正在給我們一個關於如何處理列表的練習題。 我遇到了按字母順序排序列表,但他以前從未教過我們這個,所以我不知道該怎么做。

問題是創建一個循環,該循環將 output 僅在names列表中字母表中"Thor"之前出現的名稱。 這是我嘗試過的:

names = ["Peter", "Bruce", "Steve", "Tony", "Natasha", "Clint", "Wanda", "Hope",
         "Danny", "Carol"]
thor = []
index = 1
for i in names:
  if names <= "Thor":
    thor.append ()
  index +=1
print(thor)

Python 非常適合這種事情。 例如,Python 中的for循環不需要數字索引來遍歷列表。 所以,對於你想要做的事情,它可能很簡單:

names = ["Peter", "Bruce", "Steve", "Tony", "Natasha", "Clint", "Wanda", "Hope", "Danny", "Carol"]

# Go through the list of names one at a time
for one_name in names:
    # Check to see if the current name is "less than" Thor
    if one_name < "Thor":
        # If you found a name like that, print it out
        print(one_name)

暫無
暫無

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

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