473,586 Members | 2,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

can I get the index number in for x in y loop?

>>> a='String'
for x in a: .... print x
....
S
t
r
i
n
g


can I get the index number of a in the upon loop within for x in a
loop?

Apr 3 '06 #1
9 2456
Try this:
a='String'
i=0
for x in a:

.... print i, x
.... i+=1
....
0 S
1 t
2 r
3 i
4 n
5 g

Apr 3 '06 #2
"JuHui" <ph*****@gmail. com> wrote in message
news:11******** *************@i 39g2000cwa.goog legroups.com...
a='String'
for x in a: ... print x
...
S
t
r
i
n
g
can I get the index number of a in the upon loop within for x in a
loop?


Use enumerate. See example below.

-- Paul
a = "String"
for x in a: .... print x
....
S
t
r
i
n
g for x in enumerate(a): .... print x
....
(0, 'S')
(1, 't')
(2, 'r')
(3, 'i')
(4, 'n')
(5, 'g')

Apr 3 '06 #3

JuHui wrote:
a='String'
for x in a: ... print x
...
S
t
r
i
n
g


can I get the index number of a in the upon loop within for x in a
loop?


for x, y in enumerate(a)
print x, y

Apr 3 '06 #4
which one has best performance?

a:for i in range(0,len(a))
b:for x in a
c:for x,y in enumerate(a)

but, it seems I cann't get index number with b format..:(

Apr 3 '06 #5
Em Seg, 2006-04-03 Ã*s 08:47 -0700, JuHui escreveu:
which one has best performance?
Let's see...
a:for i in range(0,len(a))
$ python2.4 -mtimeit -s 'a=[None]*100' 'for i in range(len(a)):
j = a[i]
'
100000 loops, best of 3: 17.7 usec per loop

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i in xrange(len(a)):
j = a[i]
'
100000 loops, best of 3: 16.8 usec per loop
b:for x in a
$ python2.4 -mtimeit -s 'a=[None]*100' 'i = 0
for j in a:
i += 1
'
100000 loops, best of 3: 15.7 usec per loop
c:for x,y in enumerate(a)


$ python2.4 -mtimeit -s 'a=[None]*100' 'for i, j in enumerate(a):
pass
'
100000 loops, best of 3: 12.9 usec per loop
Using enumerate is cleaner and faster.

HTH,

--
Felipe.

Apr 3 '06 #6
thanks a lot!
:)

Apr 3 '06 #7
JuHui wrote:
which one has best performance?

a:for i in range(0,len(a))
b:for x in a
c:for x,y in enumerate(a)
Read up on the timeit module and figure it out for yourself.
The answer will depend on the distribution of your data.
but, it seems I can't get index number with b format..:(


Well, that's true, but it is a bit like saying:

I cannot find the distance in meters between Paris and London with:
for i in range(10):
print i

--Scott David Daniels
sc***********@a cm.org
Apr 3 '06 #8
>>>>> "Scott" == Scott David Daniels <sc***********@ acm.org> writes:

Scott> I cannot find the distance in meters between Paris and
Scott> London with: for i in range(10): print i

Works for me

def range(x):
yield '332.8 km'

for i in range(10):
print i

....may not be considered best practice, though <wink>

JDH

Apr 3 '06 #9

JuHui wrote:
a='String'
for x in a: ... print x
...
S
t
r
i
n
g


can I get the index number of a in the upon loop within for x in a
loop?


Although enumerate is the 'right' answer, I personally prefer :
i = 0
while i < len(some_sequen ce):
val = some_sequence[i]
...
i += 1

This is so that I can manually wind 'i' backwards and forwards manually
from other parts of the code.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

Apr 3 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3114
by: Bliss | last post by:
Hi All, I have a table Truck_Journey with the following structure Tj_Date Date Tj_Truck_Id Number(5) Tj_Truck_No Varchar2(10) Tj_Km Number(9) ....
25
4900
by: sql_server_2000_user | last post by:
Hi, I have a table with about 305 million rows, and a composite primary key that consists of an ascending int and an ascending varchar(18), which is typically of length 13. Even if all the keys used the full 18 characters of the varchar, it seems to me each key should be 22 bytes, so the index should be roughly 6.4GB. However, the size of...
8
1627
by: Fan Zhang | last post by:
Dear group, I wrote a simple code trying to use the integer index of a "for" loop inside the loop. The idea is to convert it to double type and lead it into a function. However it appears I can't call the integer number directly inside the loop, otherwise, the results are not sensible. The code is as the following, int main()
6
2802
by: BB | last post by:
Hello all, I am using the currency manager in VB to navigate a dataset. I know how to use .position to loop through the rows, but what I want to do is *get* the position of the row I just added/updated, so that I can reposition the currency manager there sometime later. Seems like after I add a detached datarow to the datatable, that...
3
1906
by: Brian Piotrowski | last post by:
Hi All, I've probably done this before, but for the life of me I can't remember how I did it. I need to move values from a DB table into an array to be used for other queries. The number of records will vary, so I need to make the array dynamic. Can someone remind me how I can increment the index when I write a new record? Here's a...
1
1828
by: BeanCounterCPA | last post by:
OK, I'm sure there is an easy way to do this, but I am just a novice at Access and can not find a solution. I have a database that I used to pull a confirmation sample from by using dollar unit sampling. The selection works just fine, however, when I finish doing the selection I want to resort the database in account number sequence and then...
3
17916
by: Madmartigan | last post by:
Hello I have the following task but am battling with the final output. How do I keep two different vectors in sync and how would I retrieve the index for the maximum value of one of the vectors?? (using Dev-C++ compiler) Please see task and attempt below: TASK : 1.8.1 Exercise 1A - Temperature tracker Write a program that tracks...
1
18660
by: sksksk | last post by:
I want to achieve the following process in the smarty for $item one i should be able to get the value using loop.index, but without any luck. any help is appreciated. <?php for ($i = 1; $i <= 30; $i++) : ?> <tr> <th><?= $i ?></th>
3
1309
by: Robert Bevington | last post by:
Hi all, I ran into memory problems while tying to search and replace a very large text file. To solve this I break the file up into chunks and run the search and replace on each chunk. This works fine and has solved the OutOfMemory problem. However, on the last loop when the array c is written to CleanTMX, a number of 0x00 characters are...
0
7912
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5390
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.