【问题标题】:Repeat length of list on Python? [duplicate]在 Python 上重复列表的长度? [复制]
【发布时间】:2013-01-05 02:51:48
【问题描述】:

可能重复:
find the maximum number in a list using a loop

我正在使用循环查找 Python 列表中的最大数量。为了做到这一点,我需要有一个循环遍历整个列表。我可以使用什么循环来遍历整个列表?我是 Python 新手。

【问题讨论】:

标签: python list loops


【解决方案1】:

将一段代码重复 n 次,其中 n 是 some_list 的长度,方法如下:

for i in xrange(len(some_list)):
    # block of code

或者...

i = 0
while i < len(some_list):
    # block of code
    i = i + 1

【讨论】:

    【解决方案2】:

    您可以使用 for 循环浏览列表,例如:

    for item in lst:
        # do something with item
    

    但是,获取列表中最大项目(这似乎是您想要的)的更简单方法是:

    max(lst)
    

    【讨论】:

      【解决方案3】:
      max = None
      for e in lst:
          if max is None or e > max: max = e
      

      但正如 David 已经说过的,只需调用 max(lst) 就可以完成这项工作。

      【讨论】:

      • 虽然不要调用你的变量max
      • 另请注意,这将在 python 3 中中断,您无法比较 NoneType 和 int。
      猜你喜欢
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多