473,774 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unpaking sequences of unknown length

Hi,

I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this:

def tabulate_lists (*arbitray_numb er_of_lists):
table = zip (arbitray_numbe r_of_lists)
for record in table:
# etc ...

This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments
which it would turn into a tuple (lists in this case). Now my function does exactly the same thing ahead of zip. So, before I pass
the tuple "arbitrary_numb er_of_lists" to zip, I 'd need to unpack it but the only way I know of is into variables:

list1, list2, list3 = arbitrary_numbe r_of_lists
zip (list1, list2, list3)

With arbitrary number of lists it cannot be done this way.

Question: Is there an unpacking mechanism for cases in which I don't know--and don't need to know--how many elements I get, or an
argument passing mechanism that is the inverse of the tuplifier (*args)?

table = zip (&arbitrary_num ber_of_lists) # I invent '&' to illustrate

I preclude passing a pre-zipped table as a solution, because all function-related argument processing should be done by the
function, not by the caller. Supposing my tabulator should auto-format a printout. It would need to analyze each column (e.g.
maxima, minima, max length of strings, etc.) That would be a lot simpler with column lists than with record lists, unless I undo
what the caller had to do, because the function couldn't ... a lot of in and out ...

Of course I could code a code edit and exec () it.

names_of_lists = ','.join (['list%d' % n for n in range (len (arbitrary_numb er_of_lists)])
exec ('"%s = arbitrary_numbe r_of_lists"'% names_of_lists)
exec ('"table = zip (%s)"' % names_of_lists)

That should work, but it looks loathsome to me.
Has anyone come across a similar problem and found an elegant solution he might want to share?

Frederic
Aug 27 '06 #1
4 1884
I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this:
>
def tabulate_lists (*arbitray_numb er_of_lists):
table = zip (arbitray_numbe r_of_lists)
for record in table:
# etc ...

This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments
which it would turn into a tuple (lists in this case). Now my function does exactly the same thing ahead of zip. So, before I pass
the tuple "arbitrary_numb er_of_lists" to zip, I 'd need to unpack it but the only way I know of is into variables:

list1, list2, list3 = arbitrary_numbe r_of_lists
zip (list1, list2, list3)

I don't get your problem here. This works for me:

args = [range(5) for i in xrange(5)]

print zip(*args)
With arbitrary number of lists it cannot be done this way.

Question: Is there an unpacking mechanism for cases in which I don't know--and don't need to know--how many elements I get, or an
argument passing mechanism that is the inverse of the tuplifier (*args)?
No.

It looks a little bit as if you aren't aware of the symetry behind the *
and **-argument-passing schemes. I suggest reading up on them.

Diez
Aug 27 '06 #2
>Question: Is there an unpacking mechanism for cases in which I don't
>know--and don't need to know--how many elements I get, or an
argument passing mechanism that is the inverse of the tuplifier (*args)?

No.

It looks a little bit as if you aren't aware of the symetry behind the *
and **-argument-passing schemes. I suggest reading up on them.
Sorry - I was somewhat unconcentrated and missed the last part of the
sentence. So it is

No "generalize d", yes, the inverse of *args is foo(*args)

Sorry for the confusion.

Diez
Aug 27 '06 #3

Anthra Norell wrote:
Hi,

I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this:

def tabulate_lists (*arbitray_numb er_of_lists):
table = zip (arbitray_numbe r_of_lists)
for record in table:
# etc ...

This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of arguments
maybe I don't understand the problem properly, but you can use '*args'
as 'args' or as '*args', if you see what I mean!, ie.

def tabulate_lists (*arbitray_numb er_of_lists):
table = zip (*arbitray_numb er_of_lists)
for record in table:
# etc ...

for example:

def sum_columns(*ro ws):
for col in zip(*rows):
yield sum(col)

for i, s in enumerate( sum_columns( [1,2], [3,2], [5,1] ) ):
print 'Column %s: SUM=%s' % (i,s)

Column 0: SUM=9
Column 1: SUM=5

-----------------------------------------------------

alternatively:

import itertools as it

def sum_columns2( iterable ):
for col in it.izip( *iterable ):
yield sum(col)

def iter_rows():
yield [1,2]
yield [3,2]
yield [5,1]

print list( sum_columns2( iter_rows() ) )

#(izip isn't necessary here, zip would do.)

-----------------------------------

Gerard

Aug 27 '06 #4
I get it!
>>def f (*a):
print a
print zip (a) # My mistake
print zip (*a) # Gerard's solution.
>>f (l1, l2, l3)
([1, 2, 3], [4, 5, 6], [7, 5, 34]) # Argument: tuple of lists
[([1, 2, 3],), ([4, 5, 6],), ([7, 5, 34],)] # My mistake
[(1, 4, 7), (2, 5, 5), (3, 6, 34)] # That's what I want

Thank you all

Frederic
----- Original Message -----
From: "Gerard Flanagan" <gr********@yah oo.co.uk>
Newsgroups: comp.lang.pytho n
To: <py*********@py thon.org>
Sent: Sunday, August 27, 2006 2:59 PM
Subject: Re: unpaking sequences of unknown length

>
Anthra Norell wrote:
Hi,

I keep working around a little problem with unpacking in cases in which I don't know how many elements I get. Consider this:

def tabulate_lists (*arbitray_numb er_of_lists):
table = zip (arbitray_numbe r_of_lists)
for record in table:
# etc ...

This does not work, because the zip function also has an *arg parameter, which expects an arbitrary length enumeration of
arguments
>
maybe I don't understand the problem properly, but you can use '*args'
as 'args' or as '*args', if you see what I mean!, ie.

def tabulate_lists (*arbitray_numb er_of_lists):
table = zip (*arbitray_numb er_of_lists)
for record in table:
# etc ...

for example:

def sum_columns(*ro ws):
for col in zip(*rows):
yield sum(col)

for i, s in enumerate( sum_columns( [1,2], [3,2], [5,1] ) ):
print 'Column %s: SUM=%s' % (i,s)

Column 0: SUM=9
Column 1: SUM=5

-----------------------------------------------------

alternatively:

import itertools as it

def sum_columns2( iterable ):
for col in it.izip( *iterable ):
yield sum(col)

def iter_rows():
yield [1,2]
yield [3,2]
yield [5,1]

print list( sum_columns2( iter_rows() ) )

#(izip isn't necessary here, zip would do.)

-----------------------------------

Gerard

--
http://mail.python.org/mailman/listinfo/python-list
Aug 28 '06 #5

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

Similar topics

2
3372
by: Thomas Philips | last post by:
I have been playing around with reading strings with embedded escape sequences from files both using readline() and codecs.open() and have a question.I create a file "test.txt" with exactly one line: 1\na\n\n2\n\n3 I then open test.txt and then read it using readline(): >>> input_file=file("test.txt") >>> x=input_file.readline() >>> x
5
2436
by: Minho Chae | last post by:
Hello, python lovers!! I'm trying to create combinations of sequences. For example, if the sequence is 'acgt' and the length is 8, then I would like to have 4^8 results such as 'aaaaaaaa', 'aaaaaaac', 'aaaaaaag', 'aaaaaaat', ... 'tttttttt' Is there an easy way doing this?
3
7304
by: harrelson | last post by:
I have a list of about 2500 html escape sequences (decimal) that I need to convert to utf-8. Stuff like: 비 행 기 로 보 낼 거
4
2319
by: temp | last post by:
Hi All, I wonder could someone help me with this? What I want to do is search through a list of letters and look for adjacent groups of letters that form sequences, not in the usual way of matching say abc to another appearance later on in the list but to look for transposed patterns. The groups of letters can be made up of between 2 to 4 letters.
1
4185
by: Navin | last post by:
Ado Sort -Relate, Compute By, or Sort operations cannot be done on column(s) whose key length is unknown or exceeds 10 KB. hi, guys i have asp application running on iis 5.0 windows 2000 i use the ado sort property ...... shown below.... Rs.sort="person,lower_manager,lower_ccat_id,sac_name"
11
3373
by: TomServo | last post by:
I am writing code that needs to run on a variety of Unix systems. I am calling the statvfs and statfs system calls and I need to to convert some of the integers returned to character strings. Normally I would do this using sprintf as so: sprintf(&buffer, "%lu", integer); The problem is that I will not know if the integer values I am converting are long or long long. I also do not know if the compilers being used will support long long...
1
5473
by: SoFaraway | last post by:
Hi all, In C, to read a line from a file, we need to allocate some fixed length of memory first. However, if the line is longer than the length of the allocated memory, it can't be read correctly. Does anyone have codes that can read in a line of unknown length? Thank you very much!
23
4375
by: Himanshu Chauhan | last post by:
Hi! I was wondering, In the first parse of a singly linked list of unknown length, is it possible to know when we are at middle of the linked list? Regards --Himanshu
6
4879
by: carles | last post by:
Hi, Here, sample code where a byte array is used to fill a particular structure: fs = File.OpenRead(path); // FileStream BITMAPFILEHEADER bfh = new BITMAPFILEHEADER(); b = new byte;
0
9621
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
9454
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,...
0
10106
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9914
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...
0
8939
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
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
5355
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4012
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
3611
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.