473,394 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

looping over more than one list

When I loop over one list I use:

for item in items:
print item

but often I want to loop through two lists at once, and I've been doing
this like I would in any other language - creating an index counter and
incrementing it.
For example, (completely arbitrary), I have two strings of the same
length, and I want to return a string which, at each character
position, has the letter closest to 'A' from each of the original
strings:

def lowest(s1,s2):
s = ""
for i in xrange(len(s1)):
s += lowerChar(s1[i],s2[i])
return s

this seems unpythonic, compared to something like:

def lowest(s1,s2):
s = ""
for c1,c2 in s1,s2:
s += lowerChar(c1,c2)
return s

this doesn't work - s1,s2 becomes a tuple. Is there a way to do this
that I'm missing? I don't see it in the docs.

This works:

def lowest(s1,s2):
s = ""
for c1,c2 in [x for x in zip(s1,s2)]:
s += lowerChar(c1,c2)
return s

but it's hardly any more elegant than using a loop counter, and I'm
guessing it's performance is a lot worse - I assume that the zip
operation is extra work?

Iain

Feb 16 '06 #1
4 1461
Iain King si è profuso/a a scrivere su comp.lang.python tutte queste
elucubrazioni:

[cut]

I think you should take a look at the zip() function.

You can use for with it like this:

for elem1, elem2, elem3 in zip(list1, list2, list3):
.....

--
Alan Franzoni <al***************@gmail.com>
-
Togli .xyz dalla mia email per contattarmi.
Rremove .xyz from my address in order to contact me.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
Feb 16 '06 #2
> def lowest(s1,s2):
s = ""
for c1,c2 in [x for x in zip(s1,s2)]:
s += lowerChar(c1,c2)
return s

but it's hardly any more elegant than using a loop counter, and I'm
guessing it's performance is a lot worse - I assume that the zip
operation is extra work?

Iain


Always look in itertools for stuff like this:

http://docs.python.org/lib/itertools....html#l2h-1392

for c1, c2 in itertools.izip(s1, s2):
...

I haven't profiled it, but it makes sense that this would be fast.

Feb 16 '06 #3
Iain King <ia******@gmail.com> wrote:
...
This works:

def lowest(s1,s2):
s = ""
for c1,c2 in [x for x in zip(s1,s2)]:
s += lowerChar(c1,c2)
return s

but it's hardly any more elegant than using a loop counter, and I'm
guessing it's performance is a lot worse - I assume that the zip
operation is extra work?


1. [x for x in whateverlist] just doesn't make sense! If you need a
copy of whateverlist, just use list(whateverlist). When you don't need
a copy, like here, just use whateverlist. I.e., loop this way:

for c1, c2 in zip(s1, s2):

2. performance is destroyed by building up a big list with a += of many
small pieces. Use cStringIO (some people prefer it for style reasons)
or (what most people do) ''.join a list where you've accumulated the
results.

3. this case is ideal for build-in function map.

The body of the function could be just one statement:

return ''.join(map(lowerChar, s1, s2))

This probably gives best performance.

Also consider a genexp and avoiding the unpacking/repacking a la:

return ''.join(lowerChar(*cs) for cs in zip(s1, s2))

or better:

import itertools

and then

return ''.join(lowerChar(*cs) for cs in itertools.izip(s1, s2))

or

return ''.join(itertools.imap(lowerChar, s1, s2))

If you care about performance, use module timeit from the standard
library to measure cases of interest.

If you don't (not especially) then the first solution looks neat,
elegant, readable, and concise.

But never build up substantial strings with a loop of += of small
strings: that's O(N squared) and will MAKE you care about performance
even where you otherwise wouldn't!-)
Alex
Feb 16 '06 #4
> def lowest(s1,s2):
s = ""
for i in xrange(len(s1)):
s += lowerChar(s1[i],s2[i])
return s

this seems unpythonic, compared to something like:

def lowest(s1,s2):
s = ""
for c1,c2 in s1,s2:
s += lowerChar(c1,c2)
return s


If I understand correctly, something like

for c1,c2 in zip(s1,s2):

is what you're looking for. It will gracefully stop when it
reaches the end of the shortest input. (in your indexed
example above, if s2 is shorter than s1, it will likely
throw an out-of-bounds exception)

For your example, I'd use

def lowest(s1,s2):
return ''.join([lowerChar(c1,c2) for c1,c2 in zip(s1,s2)])

which seems to do what you describe (I understand that
appending to strings is an inefficient operation and is
better done with a join like this)

-tkc


Feb 16 '06 #5

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

Similar topics

13
by: Joseph Garvin | last post by:
When I first came to Python I did a lot of C style loops like this: for i in range(len(myarray)): print myarray Obviously the more pythonic way is: for i in my array: print i
2
by: pob | last post by:
Whats the difference between using a control or a listbox when looping thru a listbox. In example 1 it dims a listbox and an example 2 it dims a control. Please explain. Thanks in advance ...
8
by: Tommy Grav | last post by:
I have a list: a = I want to loop over a and then loop over the elements in a that is to the right of the current element of the first loop In C this would be equivalent to:
3
by: Andy | last post by:
Hello, I have the following situation: Thread A is allocating a dataset, doing some low-level calculations and storing a pointer to the dataset in a std::list via push_back. Thread B should...
10
by: Charlie Brown | last post by:
I am using something like the following function to loop through a recipe program I am working on. As I was writing it, I starting thinking this isn't going to work at all... but not I'm not so...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.