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

Home Posts Topics Members FAQ

Combining arbitrary lists

Given that

n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]

then the following code produces what I expect

for x in n[0]:
for y in n[1]:
for z in n[2]:
print [x, y, z]

--output--
[1, 4, 7]
[1, 4, 8]
[1, 5, 7]
[1, 5, 8]
...
[3, 6, 8]
-- --

How can I do this for an arbirary length of n? This reminds me of those
horrible fraction questions in 1st year comp. sci.
x = 1 + 1/(1 + 1/(1 + 1/(..... )))))... which leads me to suspect that
the simplest solution is recursive... hmmm... I'll take any suggestions.

Muchos Gracias
Nick.
Jul 18 '05 #1
7 1389
Nick wrote:
Given that

n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]

then the following code produces what I expect

for x in n[0]:
for y in n[1]:
for z in n[2]:
print [x, y, z]
....
How can I do this for an arbirary length of n?
I think this is what you're looking for:
http://aspn.activestate.com/ASPN/Coo.../Recipe/302478
Muchos Gracias


De nada ;)

--
Mariano

Jul 18 '05 #2
Mariano Draghi wrote:
Nick wrote:
Given that

n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]

then the following code produces what I expect

for x in n[0]:
for y in n[1]:
for z in n[2]:
print [x, y, z]

...

How can I do this for an arbirary length of n?

I think this is what you're looking for:
http://aspn.activestate.com/ASPN/Coo.../Recipe/302478
Muchos Gracias

De nada ;)

Okay... a) THANK-YOU, and b) HOW did you find that?

Nick.
Jul 18 '05 #3
Nick wrote:
....
I think this is what you're looking for:
http://aspn.activestate.com/ASPN/Coo.../Recipe/302478
.... Okay... a) THANK-YOU, and b) HOW did you find that?


The ASPN Python Cookbook has plenty of these kind of things.
I looked for "combinatio n" there... I think (don't remember exactly).

You can also do a search in the comp.lang.pytho n group using Google.
Try this:
http://groups.google.com/groups?q=co....lang.python.*

Regards,

--
Mariano

Jul 18 '05 #4
On Mon, 15 Nov 2004 00:57:03 -0300, Mariano Draghi <md*****@prosud .com> wrote:
Nick wrote:
Given that

n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]

then the following code produces what I expect

for x in n[0]:
for y in n[1]:
for z in n[2]:
print [x, y, z]


...

How can I do this for an arbirary length of n?


I think this is what you're looking for:
http://aspn.activestate.com/ASPN/Coo.../Recipe/302478

Following is a slightly more compact generator (unless I goofed ;-)
(untested beyoud what you see here; probably traded a little speed for code lines)
n [[1, 2, 3], [4, 5, 6], [7, 8]]
def doit(LOL): ... if not LOL: yield []; return
... for h in LOL[0]:
... for t in doit(LOL[1:]):
... yield [h] + t
... for row in doit(n): print row ...
[1, 4, 7]
[1, 4, 8]
[1, 5, 7]
[1, 5, 8]
[1, 6, 7]
[1, 6, 8]
[2, 4, 7]
[2, 4, 8]
[2, 5, 7]
[2, 5, 8]
[2, 6, 7]
[2, 6, 8]
[3, 4, 7]
[3, 4, 8]
[3, 5, 7]
[3, 5, 8]
[3, 6, 7]
[3, 6, 8]
for row in doit([[1,2],[3,4,5]]): print row

...
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
Regards,
Bengt Richter
Jul 18 '05 #5
* Nick (2004-11-15 04:28 +0100)
Given that

n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]

then the following code produces what I expect

for x in n[0]:
for y in n[1]:
for z in n[2]:
print [x, y, z]

--output--
[1, 4, 7]
[1, 4, 8]
[1, 5, 7]
[1, 5, 8]
...
[3, 6, 8]
-- --

How can I do this for an arbirary length of n?


This is the Cartesian product of three sets. Have a look at
http://www.thorstenkampe.de/python/utils.py:

def cartes(seq0, seq1, modus = 'pair'):
""" return the Cartesian Product of two sequences """
if modus == 'pair':
return [[item0, item1] for item0 in seq0 for item1 in seq1]
elif modus == 'triple':
return [item0 + [item1] for item0 in seq0 for item1 in seq1]

Then you would generate your output like this:
cartes(cartes([1, 2, 3], [4, 5, 6]), [7, 8], 'triple')

Jul 18 '05 #6
Thorsten Kampe wrote:
* Nick (2004-11-15 04:28 +0100)
Given that

n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]

then the following code produces what I expect

for x in n[0]:
for y in n[1]:
for z in n[2]:
print [x, y, z]

--output--
[1, 4, 7]
[1, 4, 8]
[1, 5, 7]
[1, 5, 8]
...
[3, 6, 8]
-- --

How can I do this for an arbirary length of n?

This is the Cartesian product of three sets. Have a look at
http://www.thorstenkampe.de/python/utils.py:

def cartes(seq0, seq1, modus = 'pair'):
""" return the Cartesian Product of two sequences """
if modus == 'pair':
return [[item0, item1] for item0 in seq0 for item1 in seq1]
elif modus == 'triple':
return [item0 + [item1] for item0 in seq0 for item1 in seq1]

Then you would generate your output like this:
cartes(cart es([1, 2, 3], [4, 5, 6]), [7, 8], 'triple')


I think the point of the question was to act on an arbitrary number of
length-3 lists.

regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
Jul 18 '05 #7
Thanks to all who replied; very helpful. Bengt Richter: that's a
lovely generator--I'm new to the whole idea of generators, but that's
very clear. I will experiment and test it.

Nick.
Jul 18 '05 #8

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

Similar topics

7
4357
by: Paddy McCarthy | last post by:
Hi, I am trying to use eval as little as possible but solve this problem. #If given:two or more lambda equations x=lambda : A < B y=lambda : C+6 >= 7 .... How do I create another lambda expression Z equivalent to
8
4157
by: mikea_59 | last post by:
I am having trouble combining similar elements. Elements can be combined if they have the same name and the same attribute values. I can handle single level elements but am having problems with multi-level elments (level of element nesting is unbound). I cannot rely on fixed element names in the translator code since the translator will be...
2
3248
by: Chris Mullins | last post by:
I've spent a bit of time over the last year trying to implement RFC 3454 (Preparation of Internationalized Strings, aka 'StringPrep'). This RFC is also a dependency for RFC 3491 (Internationalized Domain Names / IDNA) which is something that I also need to support. The problem that I've been struggling with in .NET is that of Unicode Code...
3
1817
by: Randy Yates | last post by:
Hi, We know we can build arrays of variables of the same type and arrays of functions of the same "type" (i.e., same return value and same parameters), but is there a way to automate the calling of a sequence of functions with arbitrary return types and/or parameters? -- Randy Yates Sony Ericsson Mobile Communications Research Triangle...
12
2836
by: Chadwick Boggs | last post by:
I need to perform modulo operations on extremely large numbers. The % operator is giving me number out of range errors and the mod(x, y) function simply seems to return the wrong results. Also, my numerator is in the format of a quoted string, which the mod function can't take. Desparately searching for solutions, Chadwick. ...
0
1446
by: Greg Collins [Microsoft MVP] | last post by:
I have written and posted the following articles which will prove useful to some: Display Lists in Columns Horizontally Using One Cell per Column http://www.braintrove.com/default.aspx?p=3&s=1&i=34 Display Lists in Columns Horizontally Using Individual Cells http://www.braintrove.com/default.aspx?p=3&s=1&i=33 Display Lists in Columns...
28
1579
by: walterbyrd | last post by:
Python seems to have a log of ways to do collections of arbitrary objects: lists, tuples, dictionaries. But what if I want a collection of non-arbitrary objects? A list of records, or something like that?
5
44438
by: TokiDoki | last post by:
Hi! I have a Python problem which is my last problem to solve to finish up a Django application. This is amazingly simple but I have been stuck now for a couple of days. It is embarrisingly simple. . . but not simple for me. I have two lists. I end up creating the two lists, with the end result being that each gets created at a different...
0
1099
by: John O'Hagan | last post by:
On Tue Sep 30 11:32:41 CEST 2008, Steven D'Aprano Thanks, both to you and Bruno for pointing this out, I'll certainly be using it in future.
0
7622
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
7547
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
7825
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8060
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
7588
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...
1
5452
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
3596
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...
1
1159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
865
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.