Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #75993

Re: how to get the ordinal number in list

Newsgroups comp.lang.python
Date 2014-08-10 10:45 -0700
References <mailman.12776.1407550960.18130.python-list@python.org>
Message-ID <2a9467ba-44e1-47b0-8adc-a0a3833bb209@googlegroups.com> (permalink)
Subject Re: how to get the ordinal number in list
From Rustom Mody <rustompmody@gmail.com>

Show all headers | View raw


On Saturday, August 9, 2014 7:53:22 AM UTC+5:30, luofeiyu wrote:
> >>> x=["x1","x3","x7","x5"]
>  >>> y="x3"

>   how can i get the ordinal number by some codes?

> for id ,value in enumerate(x):
>      if y==value : print(id)

> Is more simple way to do that?

I feel a bit discourteous going on a tangent and ignoring the OP...

To the OP:

The problem with your code is not that its not simple
but that it uses a print statement

To expunge the print statement you must pay a small price:
Wrap it in a function:

def search(x,y):	
  for id ,value in enumerate(x):
      if y==value : print(id)

>>> search(["x1","x2","x3"], "x2")
1

>>> # Change print to return
>>> def search(x,y):    
...    for id ,value in enumerate(x):
...        if y==value : return id
... 
>>> search(["x1","x2","x3"], "x2")
1
>>> # Works the same (SEEMINGLY)

... # Now change the return to an yield
... 
>>> def search(x,y):    
...    for id ,value in enumerate(x):
...        if y==value : yield id
... 
>>> search(["x1","x2","x3", "x2", "x5", "x2"], "x2")
<generator object search at 0x7f4e20798280>
>>> # Hmm wazzat?!
... list(search(["x1","x2","x3", "x2", "x5", "x2"], "x2"))
[1, 3, 5]

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

how to get the ordinal number in list luofeiyu <elearn2014@gmail.com> - 2014-08-09 10:22 -0700
  Re: how to get the ordinal number in list Johannes Bauer <dfnsonfsduifb@gmx.de> - 2014-08-09 14:13 +0200
  Re: how to get the ordinal number in list Rustom Mody <rustompmody@gmail.com> - 2014-08-10 10:45 -0700
    Re: how to get the ordinal number in list Rustom Mody <rustompmody@gmail.com> - 2014-08-10 11:00 -0700
  Re: how to get the ordinal number in list ismeal shanshi <stuffstorehouse2014@gmail.com> - 2014-08-10 16:56 -0700

csiph-web