【问题标题】:Using a while loop over lists in Python在 Python 中对列表使用 while 循环
【发布时间】:2013-10-30 13:27:48
【问题描述】:

所以我需要一个 while 循环,只要 list1 的最大值大于 list2 的最小值,它就会运行。现在,我有这个:

    count=0
    list1= mine
    list2= friend
    while max(list1)>min(list2):
        count+=1
        list1= list1.remove(max(list1))
        list2= list2.remove(min(list2))
    return count

但是,无法调用该函数,因为它说该对象是不可迭代的。谁能告诉我如何解决这个问题?

非常感谢你

【问题讨论】:

    标签: python list loops while-loop


    【解决方案1】:

    list.remove 不返回列表,因此一旦删除第一个值,您将分配给 list1 和 list2 变量不可迭代的对象,只需更改

    list1= list1.remove(max(list1))
    list2= list2.remove(min(list2))
    

    list1.remove(max(list1))
    list2.remove(min(list2))
    

    【讨论】:

      【解决方案2】:

      list.remove() 修改列表并返回None,因此在第一次迭代后list1list2 将是None。只需从删除行中删除分配:

      while max(list1)>min(list2):
          count+=1
          list1.remove(max(list1))
          list2.remove(min(list2))
      

      【讨论】:

        【解决方案3】:

        问题是,list.remove 返回None。虽然您可以通过替换 list1=list1.remove(...) 轻松解决此问题,但我可以向您推荐其他解决方案

        • 不要修改list1、list2,因为这会导致代码错误;
        • 有点快,因为 list.remove 不是很有效

        建议代码:

        import timeit
        from itertools import izip_longest
        
        def via_remove(l1, l2):
            count = 1
            while max(l1)>min(l2):
                count+=1
                l1.remove(max(l1))
                l2.remove(min(l2))
            return count
        
        def with_itertools(l1, l2):
            c = 1
            for l1_max, l2_min in izip_longest(sorted(l1, reverse=True), sorted(l2)):
                if l1_max <= l2_min:
                    break
                c += 1
            return c
        
        print timeit.timeit('from __main__ import via_remove; via_remove(range(1000), range(1000))', number=100)
        7.82893552113
        
        print timeit.timeit('from __main__ import with_itertools; with_itertools(range(1000), range(1000))', number=100)
        0.0196773612289
        

        【讨论】:

          猜你喜欢
          • 2021-11-13
          • 2013-07-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-05
          • 2018-02-25
          • 2021-05-25
          相关资源
          最近更新 更多