在模式后面的列表中插入值

时间:2016-04-21 20:33:17

标签: python

我有以下示例列表:

list_a = [(1, 6), 
          (6, 66), 
          (66, 72), 
          (72, 78), 
          (78, 138), 
          (138, 146), 
          (154, 208), 
          (208, 217), 
          (217, 225), 
          (225, 279), 
          (279, 288)
          .....
          ]

我需要的是:

  1. 在列表中的每6个元素之后,在此处插入一个新元素 由前一个数字和第一个数字组成的元组 前6个元组中的数字。
  2. 插入元组后, 插入由前一个数字形成的另一个数字 加1,以及前一个和第一个的最后一个数字 下一个元组的数量。
  3. 所以结果可能如下:

    list_a = [(1, 6), 
              (6, 66), 
              (66, 72), 
              (72, 78), 
              (78, 138), 
              (138, 146),
              (146, 1),     # <- first part 
              (147, 154),   # <- second part
              (154, 208), 
              (208, 217), 
              (217, 225), 
              (225, 279), 
              (279, 288)
              (288, 147)     # <- first part
              .....
              ]
    

    我试过这个,但最后一个元素丢失了

    for i in range(0, len(list_a)+1, 6):
        if i > 0:
            list_a.insert(i, (list_a[i - 1][1], list_a[i - 6][0]))
            list_a.insert(i + 1, (list_a[i - 1][1] + 1, list_a[i + 1][0],))
    

1 个答案:

答案 0 :(得分:2)

我只是通过不断追加而不是插入现有列表来构建新列表。这应该有效:

n = len(list_a)
newList = []
for i in range(0,n, 6):
    newList.append(list_a[i:i+6] ) 

    newTuple1 = (newList[-1][1], newList[i][0])
    newList.append(newTuple1)
    try:
        newTuple2 = (newTuple1[0] + 1, list_a[i+6][0])
        newList.append(newTuple2)
    except IndexError:
        print "There was no next tuple"

print newList

输出

There was no next tuple
[(1, 6), (6, 66), (66, 72), (72, 78), (78, 138), (138, 146), (146, 1), (147, 154), (154, 208), (208, 217), (217, 225), (225, 279), (279, 288), (300, 400), (400, 146)]

请注意,如果没有其他元组,那么您的示例并未指明在第二种情况下要执行的操作。假设list_a中有12个元组。然后当你到达第二组2时,没有下一个元组。

希望有所帮助。