好吧所以我需要一个输出,它告诉我同一个单词出现了多少次。我可以使用的代码或功能吗?我正在使用Grok Learning。这正是我需要的:我试图弄清楚这段代码。为此,我需要最简化的代码。这就是我的任务:
当你等着过马路时,你正在看车经过你 想知道红色或蓝色是否是汽车更受欢迎的颜色。
编写一个程序,读取每辆车的颜色字符串 开车过去,然后打印出红色汽车的数量和数量 蓝色汽车。
Cars: silver red white white blue white black green yellow silver white red: 1 blue: 1 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: yellow green white silver white blue white silver yellow pink red: 0 blue: 1
我目前的代码是:
colours = []
cars = input("Cars: ")
colours.append(cars)
if "red" in cars:
for colour in colours:
print("red:",(len(colours)))
if "blue" in cars:
print("blue:",(len(colours)))
输出错误数量的单词' red'或者' blue' 请帮助:)
答案 0 :(得分:3)
<强> ALGO 强>
<强>演示强>:
>>> day = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
>>> rain_days = raw_input("Which days had rain (use space for saparated)? ")
Which days had rain (use space for saparated)? wednesday friday
>>> day_count_without_rain = set(day).difference(days).__len__()
>>> print day_count_without_rain
5
>>>
注意强>: 在 Python 2.x
中使用raw_input
在 Python 3.x
中使用input
[编辑2 ]
使用列表及其计数方法
<强>演示强>:
>>> car_colors = raw_input("Enter string of the colour of each car that drives past")
Enter string of the colour of each car that drives past red blue Red white black green
# Convert to lower case.
>>> car_colors = car_colors.lower()
#- spit colors in to list.
>>> car_colors = car_colors.split()
>>> print "Red Color cars count:", car_colors.count("red")
Red Color cars count: 2
>>> print "Blue Color cars count:", car_colors.count("blue")
Blue Color cars count: 1
>>>
count :这将返回整数,即搜索元素在字符串或列表中出现的次数。
<强>演示强>:
>>> l = [1,2,3,1, 0]
>>> l.count(1)
2
>>> l.count(11)
0
>>> a = "aagghhttee"
>>> a.count("a")
2
>>> a.count("aa")
1
>>> a.count("aaa")
0
>>>
答案 1 :(得分:1)
import collections
colorCounts = collections.defaultdict(int, collections.Counter(input("cars: ").lower().split()))
needed = 'red blue'.split()
for n in needed:
print("{}:".format(n), colorCounts[n])
答案 2 :(得分:0)
这是最简单的解决方案,也是Grok Learning提供的示例解决方案:
cars = input('Cars: ')
cars = cars.split()
red = blue = 0
for car in cars:
if car == 'red':
red += 1
elif car == 'blue':
blue += 1
print('red:', red)
print('blue:', blue)
我希望这会有所帮助!