【问题标题】:How to sort and remove items from list base on alphabetical?如何根据字母顺序对列表中的项目进行排序和删除?
【发布时间】:2021-02-07 23:21:27
【问题描述】:

我的老师正在给我们一个关于如何处理列表的练习题。我遇到了按字母顺序排序列表,但他以前从未教过我们这个,所以我不知道该怎么做。

问题在于创建一个循环,该循环将仅输出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)

【问题讨论】:

  • 您的意思是if i &lt;= "Thor".append(i) 吗?
  • 天啊,我想了很多,但我没想到,哈哈,我觉得我想得不够。非常感谢!
  • 功能方法:thor = list(filter(lambda x: x &lt; 'Thor', names))。顺便说一句,您是否发现您的解决方案中不需要index
  • 列表可以在没有索引的情况下检查列表中的下一项吗?
  • 你不需要索引。您不会在任何地方使用值 index 来访问该列表。你有没有想过命名一个变量index 会自动把它变成某种奇怪的 lis 访问东西?列表是可迭代的,因此在处理 for 循环时,i 将绑定到一个接一个的元素。

标签: python list alphabetical


【解决方案1】:

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)

【讨论】:

  • 这比我的代码简单多了哈哈,非常感谢,我试试看!
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多