在Python中计算单个单词

在Python中计算单个单词,python,list,Python,List,所以我需要计算python输入列表中的单个单词(特别是红色和蓝色)。 但是,它不能是例如redish或bluemaybe。 下面是我所做的(我尝试了if循环来捕捉它,但没有成功。) 可以循环遍历列表,然后返回值 拆分和追加不是必需的。当遇到编码问题时,尽量在不牺牲任何实质内容的情况下找到最简单、最简洁的答案 for words in cars: cars.count('red', 'blue') return whatever_you_want 下面的工作 # replace

所以我需要计算python输入列表中的单个单词(特别是红色和蓝色)。 但是,它不能是例如redish或bluemaybe。 下面是我所做的(我尝试了if循环来捕捉它,但没有成功。)


可以循环遍历列表,然后返回值 拆分和追加不是必需的。当遇到编码问题时,尽量在不牺牲任何实质内容的情况下找到最简单、最简洁的答案

for words in cars:
    cars.count('red', 'blue')
    return whatever_you_want 
下面的工作

# replace by 'carsStr = input("Cars: ")' if you wish
carsStr = "rad blue blueish redish red blue red" 
# str.split() returns a list of strings, never in-place
cars = carsStr.split()
r = cars.count('red')
b = cars.count('blue')
print("red:",r)
print("blue:",b)
以下是你的错误:

  • 执行
    cars.append(car)
    然后执行
    car.split()
    不会“展开”
    cars
    列表中的
    car
    字符串
  • car.split()。在您的情况下,该列表将丢失,因为您没有将其分配给变量
  • 您也从不重复使用
    汽车
    列表

如果你不想要一个更完整的计数工具,请参见。

问题出在哪里?为什么不把它分成几个字(有一个很好的答案,如何做到这一点),然后把这些字输入到
集合中。计数
并从中得到计数?制造商不把他们的汽车颜色称为“红色”和“蓝色”,他们使用像樱桃这样的词,斗牛士和塔希提岛。
# replace by 'carsStr = input("Cars: ")' if you wish
carsStr = "rad blue blueish redish red blue red" 
# str.split() returns a list of strings, never in-place
cars = carsStr.split()
r = cars.count('red')
b = cars.count('blue')
print("red:",r)
print("blue:",b)