473,809 Members | 2,742 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1489
Iain King si è profuso/a a scrivere su comp.lang.pytho n 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(whateverli st). 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(low erChar, s1, s2))

This probably gives best performance.

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

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

or better:

import itertools

and then

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

or

return ''.join(itertoo ls.imap(lowerCh ar, 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
14735
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
16100
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 Example 1 from Allen Browne MVP Access To use a Multiselect list box for criteria for a report, you need to loop through its ItemsSelected collection to create a string that can act as the WhereCondition for your report.
8
1515
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
3732
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 retrieve the pointer to the first dataset in the list, remove it from the list, and do some high level analysis. The problem now is, how do I efficiently retrieve the pointer?
10
1289
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 sure. Will this code work, or cause me problems? Private Sub DoSomething() Dim viCount As Integer = _varianceList.Count For i As Integer = 0 To viCount - 1 Dim vi As ProductionVarianceItem = _varianceList(i) vi.ProductionOut =...
0
9721
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9601
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10379
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10115
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7660
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.