a = [1,1,1,4,4,4,5]
b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607,20150608]
c = zip(a,b)
output = []
for i in range(0, len(c)-1):
if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3:
output.append(c[i])
print output
This code searches 2 lists using conditionals. If element n == element n+1 in list a AND (element n+1) - (element n)<= 3 in list b .....it prints the results. The problem I'm having is that it cuts off 1 element that should be printing. (ie This code will output
[(1, 20150602), (1, 20150603), (4, 20150605), (4, 20150606)]
but should be outputting
[(1, 20150602), (1, 20150603), (1,20150604), (4, 20150605), (4, 20150606), (4, 20150607)])
See the second append to the output list. :)
In [14]:
a = [1,1,1,4,4,4,5]
b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607,20150608]
c = zip(a,b)
output = []
for i in range(0, len(c)-1):
if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3:
output.append(c[i])
output.append(c[i+1])
output = sorted(list(set(output)))
print output
[(1, 20150602), (1, 20150603), (1, 20150604), (4, 20150605), (4, 20150606), (4, 20150607)]
a = [1,1,1,4,4,4,5]
b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607,20150608]
c = zip(a,b)
output = []
for i in range(0, len(c)-1):
if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3:
output.append(c[i])
elif c[i][0] != c[i+1][0]:
print 'equality failed for numbers: %d and %d' % (c[i][0], c[i+1][0])
elif c[i+1][1] - c[i][1] > 3:
print 'Subtraction is greater than three for: %d and %d' % (c[i][1], c[i+1][1])
print output
output:
equality failed for numbers: 1 and 4
equality failed for numbers: 4 and 5
[(1, 20150602), (1, 20150603), (4, 20150605), (4, 20150606)]
The reason you are missing two elements is because when i
in the for loop is 2 c[i][0]
will return 1. Now, when this section of the if statement is performed: c[i][0] == c[i+1][0]
it returns false because c[i][0]
returns 1 and c[i+1][0]
returns 4 and they do not equal each other. The same happens when i
is equal to 5.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.