skip next item in list

A

ahlongxp

list=('a','d','c','d')
for a in list:
if a=='a' :
#skip the letter affer 'a'

what am I supposed to do?
 
A

Andre Engels

2007/6/11 said:
list=('a','d','c','d')
for a in list:
if a=='a' :
#skip the letter affer 'a'

what am I supposed to do?

There might be better ways to do it, but I would do:

flag_last_a = False
for a in list:
if flag_last_a:
flag_last_a = False
continue
if a=='a':
flag_last_a = True
# Whatever is done when you don't skip
 
D

Diez B. Roggisch

ahlongxp said:
list=('a','d','c','d')
for a in list:
if a=='a' :
#skip the letter affer 'a'

what am I supposed to do?

First - don't use list as name, as it is a builtins-name and shadowing is
likely to produce errors at some point.

list_iterator = iter(('a','d','c','d'))

for a in list_iterator:
if a == 'a':
list_iterator.next()
...

should do the trick.



Diez
 
D

danmcleran

list=('a','d','c','d')
for a in list:
if a=='a' :
#skip the letter affer 'a'

what am I supposed to do?


You could do this with itertools.ifilter and an predicate (pred) for a
more OO solution. I've created 2 lists, the source list (l) and the
expected answer (ans). Make sure this is what you meant in your
problem statement:

import itertools

l = ['a', 'b', 'c', 'a', 'd', 'e', 'f', 'a', 'g', 'h']
ans = ['a', 'c', 'a', 'e', 'f', 'a', 'h']

class pred(object):
def __init__(self):
self.last = None

def __call__(self, arg):
result = None

if self.last == 'a':
result = False
else:
result = True

self.last = arg

return result

i = itertools.ifilter(pred(), l)

result = list(i)

print result
print ans

assert result == ans

print 'done'
 
R

Rafael Darder Calvo

There might be better ways to do it, but I would do:

flag_last_a = False
for a in list:
if flag_last_a:
flag_last_a = False
continue
if a=='a':
flag_last_a = True
# Whatever is done when you don't skip
another way:

def skip_after(l):
i = iter(l)
for x in i:
yield x
while x == 'a':
x = i.next()

depending on what to do in case of consecutive 'a's, change the
'while' for an 'if'
list(skip_after('spam aand eggs'))
['s', 'p', 'a', ' ', 'a', 'd', ' ', 'e', 'g', 'g', 's']
 
D

Duncan Smith

ahlongxp said:
list=('a','d','c','d')
for a in list:
if a=='a' :
#skip the letter affer 'a'

what am I supposed to do?

Maybe,
it = iter(['a','d','c','d'])
for item in it:
print item
if item == 'a':
x = it.next()


a
c
d
The binding of a name to it.next() is unnecessary. It just prevents 'd'
being printed.

Duncan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top