【问题标题】:Python while loop , how can I reach a given list?Python while循环,我怎样才能到达给定的列表?
【发布时间】: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


【解决方案1】:

我相信你想做的是这样的:

items = ['apple', 55, 1.2, 'banana', lambda a: a, 'pear', None, 'cherry',  """Hello world!""", '''The Who''', ("a", 5), [("a", "5"), ("b", 3)]]

i = 0

for item in items:
   if(type(item) == str):
       i += 1

print(f'There are {i} string' if i > 0 else "There are no string values")

【讨论】:

  • 是的,这就是我想要的。非常感谢,现在我将使用 while 循环编写代码。
猜你喜欢
  • 2022-12-18
  • 1970-01-01
  • 2017-02-10
  • 2018-05-14
  • 2013-08-18
  • 2019-07-13
  • 2014-05-14
  • 2012-11-30
  • 2020-03-11
相关资源
最近更新 更多