【问题标题】:Python3 : How to Use enumerate() to Print total items in a list?Python3:如何使用 enumerate() 打印列表中的总项目?
【发布时间】:2021-05-01 11:10:57
【问题描述】:

我没有使用len,而是使用enumerate 函数。在里面,我怎样才能得到项目的总数?

示例代码:-

data = ['bat','cat','eat','fat','தொப்பி','எலி']
for itemNum, item in enumerate(data):
    print(itemNum+1, end='')

结果:123456

预期结果:6

【问题讨论】:

    标签: python-3.7 enumerate


    【解决方案1】:

    您可以通过以下代码实现此目的

    data = ['bat','cat','eat','fat','தொப்பி','எலி']
    count = 0
    for itemNum, item in enumerate(data):
        count = count + 1
        
    print(count)
        
    

    【讨论】:

      【解决方案2】:
      i=0
      for itemNum, item in enumerate(data):
          i=i+1
      
      print(i)
      

      【讨论】:

        【解决方案3】:

        使用enumerate是为了避免上面所说的,计数方法。比较时,我认为枚举功能是高级功能。希望我在这个问题上是正确的。

        data = ['bat','cat','eat','fat','தொப்பி','எலி']
        py_no= [  0,    1,    2,    3,    4,   5 ]
        human= [  1,    2,    3,    4,    5,   6 ]
        
        for itemNum, item in enumerate(data):
            itemNum2tuple = tuple(str(itemNum+1)) # immutable; for human number adding +1
            itemNum2tuple_string = itemNum2tuple[0] # to avoid brackets, ...
        print(itemNum2tuple_string) # indentation for the loop end.
        print(int(itemNum2tuple_string)) # to further need, changing as integer
        

        预期输出: 6

        【讨论】:

          猜你喜欢
          • 2017-10-28
          • 1970-01-01
          • 2020-09-26
          • 2017-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多