【发布时间】:2020-02-18 10:36:15
【问题描述】:
items = ['apple', 55, 1.2, 'banana', lambda a: a,
'pear', None, 'cherry', """Hello world!""",
'''The Who''', ("a", 5), [("a", "5"), ("b", 3)]]
i = ""
while i in items:
if(items == type(str)):
print("There are 6 string")
if(items != type(str)):
print("There ara no string value")
我已经编写了这个程序,但它不工作。
如何使用type() 方法到达列表并打印此列表中的多少字符串?
之后; 因为输入列表中有多个字符串值。但是,如果没有字符串值,您的程序应该输出
There are no string values
如果只有一个字符串值,那么应该打印出来
There is a single string value.
这是我的作业,但我被这个问题困住了。 另外,我可以用for循环吗?
【问题讨论】:
-
print('There are {} string items in the list'.format(sum(1 for item in items if isinstance(item, str)))) -
您的问题似乎缺少一些细节 -
items列表中可以有多个lists 吗?即使items中有一个list- 如果有多个字符串,输出应该是什么? -
@Chris_Rands ,它确实有效,但我必须使用 type(.) 方法。带有一个while循环。
-
@Mortz, 编写一个 Python 程序,该程序使用
while-loop 来计算并打印给定列表顶层包含多少str(字符串)值。例如,当您通过以下列表运行程序时。
标签: python python-3.x list loops while-loop