def doubles(lst):
for i in range(len(lst)):
if lst[i]*2==lst[i+1]:
print(lst[i+1],end=' ')
What I get:
8 -24 6 12 24 Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
doubles( [4,8,-12,-24,48,3,6,12,24,2])
line 32, in doubles
if lst[i+1]:
IndexError: list index out of range
The output is what I want 8 -24 6 12 24
, but I'm not sure how to get rid of the index error for this function. Any ideas?
Loop until the one but last element :
def doubles(lst):
for i in range(len(lst) - 1):
if lst[i] * 2 == lst[i + 1]:
print(lst[i + 1], end=' ')
because otherwise you try to access lst[i + 1]
which is guaranteed to be 1 index further than there are elements in the list.
You can also loop directly over lst
, together with enumerate()
to produce the indices:
def doubles(lst):
for i, elem in enumerate(lst[:-1]):
if elem * 2 == lst[i + 1]:
print(lst[i + 1], end=' ')
or you can use zip()
to pair up elements with the next element:
def doubles(lst):
for i, j in zip(lst, lst[1:]):
if i * 2 == j:
print(j, end=' ')
which you could put into a generator expression:
def doubles(lst):
print(*(j for i, j in zip(lst, lst[1:]) if i * 2 == j), sep=' ')
Demo of all of these:
>>> [4,8,-12,-24,48,3,6,12,24,2]
[4, 8, -12, -24, 48, 3, 6, 12, 24, 2]
>>> lst = [4,8,-12,-24,48,3,6,12,24,2]
>>> for i in range(len(lst) - 1):
... if lst[i] * 2 == lst[i + 1]:
... print(lst[i + 1], end=' ')
...
8 -24 6 12 24 >>>
>>> for i, elem in enumerate(lst[:-1]):
... if elem * 2 == lst[i + 1]:
... print(lst[i + 1], end=' ')
...
8 -24 6 12 24 >>>
>>> for i, j in zip(lst, lst[1:]):
... if i * 2 == j:
... print(j, end=' ')
...
8 -24 6 12 24 >>>
>>> print(*(j for i, j in zip(lst, lst[1:]) if i * 2 == j), sep=' ')
8 -24 6 12 24
You can use the pairwise
recipe from the itertools docs :
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def doubles(lst):
for x,y in pairwise(lst):
if x * 2 == y:
print(y, end=' ')
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.