【问题标题】:Comparing every element in a list with the next one将列表中的每个元素与下一个元素进行比较
【发布时间】:2019-07-19 21:32:14
【问题描述】:

我有一个整数列表a,我想遍历它的每个元素,如果该元素比列表中的下一个元素(即将到来的索引邻居)更小或大小相同,我想要将元素转换为字符串并将“000”连接到它上面。但如果它比下一个元素大,我想将“111”连接到它上面。

我使用 Python 3.7.3。

这是我已经尝试过的:

a = [41433, 23947, 10128, 89128, 29523, 47106]

for I in a:
      if a[I] <= a[I+1]:
             a[I] = str(a[I] + "000")
      else:
             a[I] = str(a[I] + "111")

我实际上尝试了很多,但没有任何效果。 当我运行代码时,总是得到“IndexError: list index out of range”。

我是Python新手,有人知道解决方案吗?

【问题讨论】:

  • 根据您的描述,除最后一个元素外,所有元素都转换为字符串。正确的?所以,for i in range(len(a)-1): a[i] = str(a[i]) + ('000' if a[i] &lt;= a[i+1] else '111')
  • 那么您的预期输出是什么,列表中最后一项无法与其后一项进行比较的处理方式是什么?
  • 你的预期输出是什么?

标签: python python-3.x


【解决方案1】:

您的 I 值不是索引,它是 a(41433、23947 等)中的一个元素,因此 a[41433] 不存在。

尝试使用范围

for i in range(0, len(a)-1):
  if a[i] <= a[i+1]:
    a[i] = str(a[i]) + "000"
  else:
    a[i] = str(a[i]) + "111"

【讨论】:

    【解决方案2】:

    我会使用 itertools 为您的列表创建两个迭代器,并将它们压缩在一起,以便您获得成对的连续值:

    from itertools import tee
    
    i1, i2 = tee(a)
    next(i2, None)    # advances i2 by one step
    pairs = zip(i1, i2)
    a = [str(elem1)+'000' 
            if elem1 <= elem2 else str(elem1)+'111' 
            for elem1, elem2 in pairs]
    

    【讨论】:

      【解决方案3】:

      enumerate 非常适合这个用例。它还将增加可读性:

      a = [41433, 23947, 10128, 89128, 29523, 47106]                  
      
      for index, elem in enumerate(a[:-1]):                           
          if a[index] <= a[index+1]:                                  
              a[index] = str(a[index]) + "000"                     
          else:                                                       
              a[index] = str(a[index]) + "111"                     
      print(a) 
      

      ['41433111', '23947111', '10128000', '89128111', '29523000', 47106]

      【讨论】:

        【解决方案4】:

        pythonic 方法是使用enumerate,它生成(index, list[index) 的元组。

        for idx, val in enumerate(a[:-1]):
            if val <= a[idx+1]:
                a[idx] = str(a[idx]) + "000"
            else:
                a[idx] = str(a[idx]) + "111"
        

        备注
        使用a[:-1] 循环直到倒数第二个项目,这样您就不会遇到索引越界错误。

        【讨论】:

          猜你喜欢
          • 2020-07-03
          • 2019-01-19
          • 2013-06-06
          • 1970-01-01
          • 1970-01-01
          • 2020-03-04
          • 2015-04-02
          • 2017-10-30
          相关资源
          最近更新 更多