我是编程atm的新手。我搜索了论坛,但没有一个结果适用于我的情况(除非我弄错了,但相信我,我做的第一件事就是google)。如果你有时间,请帮助我。
编写一个python程序,提示用户输入名字列表并将它们存储在列表中。该程序应显示字母“a”出现在列表中的次数。
现在我觉得我有完美的代码。但每次程序只计算列表中第一个单词中“a”的数量!?
terminate = False
position = 0
name_list = [ ]
while not terminate:
name = str(input('Please enter name: '))
name_list.append(name)
response = input('Add more names? y/n: ')
if response == 'n':
terminate = True
print(name_list)
for t in name_list:
tally = name_list[position].count('a')
position = position + 1
print("The numer of 'a' is: ", tally)
如果有人有时间提供帮助,我会很感激。
答案 0 :(得分:1)
有几点:
tally
作为累加器,但实际上并没有添加它。position
索引器,for t in name_list
已遍历列表中的所有名称,在for循环的每次迭代中t
都是name_list
的名称1}}。修复内循环
terminate = False
# position = 0 <-- this is not needed anywhere
name_list = [ ]
while not terminate:
name = str(input('Please enter name: '))
name_list.append(name)
response = input('Add more names? y/n: ')
if response == 'n':
terminate = True
print(name_list)
tally = 0 # initialise tally
for t in name_list:
tally += t.count('a') # increment tally
print("The numer of 'a' is: ", tally)
答案 1 :(得分:0)
您的代码对我来说并不完全可以理解。可能是因为有些东西丢失了。所以,我假设你已经有了名单。在您提供的代码中,每次计算列表中名称中的a数时,都会覆盖tally
。除了代码中的其他可能的错误(可能在创建名称列表时 - 我为此使用了while循环),你应该写
tally += name_list[position].count('a')
等于
tally = tally + name_list[position].count('a')
代替你的
tally = name_list[position].count('a')
答案 2 :(得分:0)
我建议你摆脱for循环和位置计数器。如果您想要所有'a'
的总和,则必须为所有名称求和tally
:
terminate = False
name_list = []
total = 0
while "Adding more names":
name = str(input('Please enter name: '))
name_list.append(name)
tally = name.count('a')
total += tally
print("The numer of 'a' in current name is: ", tally)
if input('Add more names? y/n: ') == 'n':
break
print(name_list)
print("The numer of 'a' is: ", total)
答案 3 :(得分:0)
terminate = False
position = 0
name_list = [ ]
tally = 0
while not terminate:
name = str(input('Please enter name: '))
name_list.append(name)
response = input('Add more names? y/n: ')
if response == 'n':
terminate = True
print(name_list)
for t in name_list:
#tally = name_list[position].count('a')
tally += name_list[position].count('a')
position = position + 1
print("The numer of 'a' is: ", tally)
初始化tally = 0并且输入&#34; tally = name_list [position] .count(&#39; a&#39;)&#34;使用&#34; tally + = name_list [position] .count(&#39; a&#39;)&#34;如果你必须计算&#34; a&#34;在整个列表中,您必须更新计数值