我正在尝试检查列表中的2个元素是否递增1。
For instance, in a list like this [1,3,4,5,6,7,9,11,12]
, my code should return a new list like this [3,4,5,6,11,12]
这是我的代码:
same = [1,3,4,5,6,7,9,11,12]
new_datalist = []
index = 0
for k in same:
try:
new_index = index+1
if k+1 == same[new_index]:
new_datalist.append(k)
new_datalist.append(k+1)
index += 1
except:
pass
new_datalist
But it is returning this - [3, 4, 4, 5, 5, 6, 6, 7, 11, 12]
我该如何解决?
您需要修复算法-尽可能接近使用的算法
一种更pythonic的方式是使用zip():
您正在两次添加元素
引导您完成...
On
k == 3
,k + 1 == 4
, andsame[new_index] == 4
, so you add bothk
andk + 1
. On the next iteration, you havek == 4
,k + 1 == 5
, andsame[new_index] == 5
, so you add 4 and 5. You are double counting 4.Get rid of the
new_datalist.append(k+1)
line.