【问题标题】:print 0 when counting a list item that is not in list计算不在列表中的列表项时打印 0
【发布时间】:2017-10-23 19:53:38
【问题描述】:

如果未从用户输入列表中输入红色,我将坚持生成“红色:0”。如果我输入说“蓝绿白黑银银银蓝银黑银白银白银白白黄红红银红”,输出将是: 红色:3 蓝色:2

我想要它做的。如果我从该列表中取出红色,则输出为:

蓝色:2....我希望它是:

红色:0 蓝色:2

colors = []
cars = input("Cars: ")
colors.append(cars)
if "red" in cars:
  for color in colors:
    print("red:", cars.count("red"))
if "blue" in cars: 
   print("blue:", cars.count("blue"))

【问题讨论】:

  • 在拆分的单词列表上使用collections.Counter

标签: python html css list count


【解决方案1】:

处理您的示例代码,您需要做的就是删除ifs:

cars = input("Cars: ")
print("red:", cars.count("red"))
print("blue:", cars.count("blue"))

演示:

>>> Cars: blue green white black silver silver silver blue silver black silver white white silver white white yellow red red silver red
red: 3
blue: 2

>>> Cars: blue green white black silver silver silver blue silver black silver white white silver white white yellow
red: 0
blue: 2

【讨论】:

    【解决方案2】:

    为什么要使用 if 和 for 子句;它们不是必需的,跳过它们可以解决您的问题:

    colors = []
    cars = input("Cars: ")
    colors.append(cars)
    print("red:", cars.count("red"))
    print("blue:", cars.count("blue"))
    

    【讨论】:

      【解决方案3】:

      我建议您使用 split 方法从您的输入字符串创建一个列表。 然后要打印红色结果,您还需要删除 if 语句,因此您的最终代码将是这样的:

      colors = []
      cars = input("Cars: ")
      colors = cars.split()
      print("red:", colors.count("red"))
      print("blue:", colors.count("blue"))
      

      【讨论】:

      • 太棒了!效果很好!现在我的问题是,如果红色这个词出现在诸如“redish”之类的词中,它就不算数.....
      • 做你要求的事情将定义一个新的函数来计算你需要什么。 def counts(list, color): n = 0 for item in list: if color in item: n = n + 1 return n 然后你的打印将是(蓝色相同):print("red:", counts(colors, "red")
      • 如果评论格式有点混乱,我很抱歉,但我是新手,我不知道它是如何工作的。 (注意缩进)
      猜你喜欢
      • 2018-03-13
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2016-06-05
      • 2020-01-19
      • 2018-09-04
      相关资源
      最近更新 更多