Pergunta

I have something like this:

for i, item in enumerate(weapons):
    print "%s : %s" % (i, item)
print "#####"
for i, item in enumerate(weapons):
    if item is not 'bananas':
        print "%s : %s"%(i, item)

And I get this:

0: apples
1: bananas
2: oranges
3: pears
4: coconuts
#####
0: apples
2: oranges
3: pears
4: coconuts

But I would like to increase the 'i' only if it's used, creating

0: apples
1: oranges
2: pears
3: coconuts

What's the most pythonic way of doing this? I was using a predefined variable outside the for-loop and increasing it by 1 every iteration. Like this.

i = 0
for item in weapons:
    if item is not 'bananas':
        print "%s : %s"%(i, item)
        i += 1

But it seems very ugly.

Foi útil?

Solução

Send filtered items to the enumerate:

weapons = 'apples', 'bananas', 'oranges', 'pears', 'coconuts',
for i, item in enumerate(item for item in weapons if item != 'bananas'):
    print "%s : %s"%(i, item)

output:

0 : apples
1 : oranges
2 : pears
3 : coconuts

Outras dicas

If you have multiple items which you don't want to show (based on falsetru's answer):

do_not_show = ['bananas', 'oranges']
for i, item in enumerate(itm for itm in weapons if itm not in do_not_show):
    print "%s : %s"%(i, item)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top