【问题标题】:How can I count strings in a list with while loop in Python?如何在 Python 中使用 while 循环计算列表中的字符串?
【发布时间】:2021-10-12 18:24:50
【问题描述】:

假设我有一个包含 0 个或多个元素的列表,如何在不使用 count() 或 while 循环以外的其他方法的情况下返回其中的字符串数量?我尝试了下面的代码,但它总是崩溃。

values = ["one", "two", [], 6]

def count_str(values):
    index = 0
    while index <= len(values):
        if type(values[index]) == str:
            index += 1
    return index

【问题讨论】:

  • 问题是你使用相同的索引来迭代值,并对字符串进行计数......所以当它不是字符串时,索引不会改变,并且循环永远不会结束。使用两个变量。

标签: python string while-loop


【解决方案1】:

问题是你有一个无限循环,因为你只在它是一个字符串时增加索引,鉴于并非所有实例都是,循环永远不会结束

尝试:

values = ["one", "two", [], 6]

def count_str(values):
  index = 0
  counter = 0
  while index <= len(values)-1:
    if type(values[index]) == str:
      counter += 1
    index += 1
  return counter

ans = count_str(values)
print(ans)

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2021-02-25
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多