Python 循环的代码计数字母
Python code count letters for loop
写一个函数 countletter() 应该有一个 'for' 循环
通过下面的列表并打印城市名称和数量
城市名称中的字母。您可以使用 len() 函数。
citylist = ["Kentucky","New York","LA", "Toronto",
"Boston","District of Columbia"]
我在 Spyder 中使用 Python 3.5。我无法从列表中提取字母,然后在 for 循环中将它们打印出来。
我有:
def countletter(citylist):
city = len(citylist)
ct = 0
for i in citylist:
city = (ne[i])
然后我卡住了。我担心这可能是完全错误的。我也在纠结如何打印这个。
输出应该是:
肯塔基州有 8 个字母。
纽约有 12 个字母。
LA 有 2 个字母。
多伦多有 7 个字母。
波士顿有 6 个字母。
哥伦比亚特区有 20 个字母。
感谢您的帮助!
def countletter(citylist):
for index,city in enumerate(citylist):
print (index,' : ',city," has ";len(city);" letters".
应该给:
1 : 肯塔基州有 8 个字母。
2:纽约有8个字母。
...
您不需要使用索引。只需迭代 citylist
; for
循环将生成每个城市。
def countletter(citylist):
for city in citylist:
n = len(city)
print(city, 'has', n, 'letters.')
citylist = ["Kentucky","New York","LA", "Toronto", "Boston","District of Columbia"]
countletter(citylist)
输出:
Kentucky has 8 letters.
New York has 8 letters.
LA has 2 letters.
Toronto has 7 letters.
Boston has 6 letters.
District of Columbia has 20 letters.
写一个函数 countletter() 应该有一个 'for' 循环 通过下面的列表并打印城市名称和数量 城市名称中的字母。您可以使用 len() 函数。
citylist = ["Kentucky","New York","LA", "Toronto",
"Boston","District of Columbia"]
我在 Spyder 中使用 Python 3.5。我无法从列表中提取字母,然后在 for 循环中将它们打印出来。
我有:
def countletter(citylist):
city = len(citylist)
ct = 0
for i in citylist:
city = (ne[i])
然后我卡住了。我担心这可能是完全错误的。我也在纠结如何打印这个。
输出应该是:
肯塔基州有 8 个字母。
纽约有 12 个字母。
LA 有 2 个字母。
多伦多有 7 个字母。
波士顿有 6 个字母。
哥伦比亚特区有 20 个字母。
感谢您的帮助!
def countletter(citylist):
for index,city in enumerate(citylist):
print (index,' : ',city," has ";len(city);" letters".
应该给:
1 : 肯塔基州有 8 个字母。
2:纽约有8个字母。
...
您不需要使用索引。只需迭代 citylist
; for
循环将生成每个城市。
def countletter(citylist):
for city in citylist:
n = len(city)
print(city, 'has', n, 'letters.')
citylist = ["Kentucky","New York","LA", "Toronto", "Boston","District of Columbia"]
countletter(citylist)
输出:
Kentucky has 8 letters.
New York has 8 letters.
LA has 2 letters.
Toronto has 7 letters.
Boston has 6 letters.
District of Columbia has 20 letters.