how to get the ordinal number in list
Rustom Mody
rustompmody at gmail.com
Sun Aug 10 13:45:03 EDT 2014
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]
More information about the Python-list
mailing list