首页 > 解决方案 > 如何让此代码对上面给出的名称进行计数和排序?(初学者)

问题描述

name = ["Safi", "Safi", "Safi", "Umaima", "Arsalah", "Farooq", "Ben", "Ben"]
list = ["Safi", "Safi", "Safi", "Umaima", "Arsalah", "Farooq", "Ben", "Ben"]
a = input("What would you like to know about the following list?")

if a == "Sort this list":
  print (list.sort())

if a == "What is the Number of "+a+"'s":
  print(list.count(+a))
else:
  print("I don't understand")

该代码不想接受用户的输入,因为它只是跳过了用户的输入并且没有集成它。

标签: pythonlist

解决方案


主要原因是 sort() 函数不返回任何内容,因此您必须在排序后打印列表:

name = ["Safi", "Safi", "Safi", "Umaima", "Arsalah", "Farooq", "Ben", "Ben"]
list = ["Safi", "Safi", "Safi", "Umaima", "Arsalah", "Farooq", "Ben", "Ben"]
a = input("What would you like to know about the following list?")
if a == "sort":
    list.sort()
    print (list)
if a == "count":
    keyword = input("Which string to you want to count ?")
    print (list.count(keyword)) #I think you want to count the occurence of the input word

推荐阅读