python - Python 函数接受一个值列表并返回该列表在顶层包含多少个字符串
问题描述
我正在尝试编写函数以使用 while 循环打印给定列表中有多少个字符串。
我已经使用 for 循环打印出 6 是正确的,但是当我尝试使用 while 循环时,我看不到任何打印,没有打印任何错误。
def count_strings(items):
i = 0
while i < len(items):
if(type(items) == str):
i += 1
return i
t = ['apple', 55, 1.2, 'banana', lambda a: a, 'pear', None, 'cherry', """Hello world!""", -2, '''The Who''', ("a", 5), [("a", "5"), ("b", 3)]]
print(count_strings(t))
解决方案
您同时使用i
循环变量和字符串计数。您应该使用不同的变量。还有,type(items)
总是list
。你应该检查一下type(items[i])
。
def count_strings(items):
i = 0
count = 0
while i < len(items):
if type(items[i]) == str:
count += 1
i += 1
return count
如果 while 循环不是必需的,您可以使用列表理解和sum
:
sum([1 if type(x) == str else 0 for x in items])
推荐阅读
- scipy - Scipy最小化函数约束声明问题
- html - PSD to bootstrap - 请建议保持 HTML 与大 PSD 相同
- javascript - JSON 文件中的 HTML 标记显示为纯文本而不是真正的 HTML 标记
- multithreading - 在并行迭代器中执行计算,然后将其提供给单线程迭代器?
- google-apps-script - 在谷歌表格中取消选择或保存当前单元格
- spring-boot - 卡夫卡保留.字节| 手动确认
- html - Tailwind CSS 不必要的空格
- javascript - 我需要获取创建的频道的ID,但我不知道该怎么做?(discord.js)
- excel - Excel vba匹配两列
- c# - 如何使属性字段显示在 VS 属性网格中,而不是自定义属性网格中?