首页 > 解决方案 > 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))

标签: pythonpython-3.x

解决方案


您同时使用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])

推荐阅读