Given a bunch of arrays, if I want to create tuples, there is
zip(arrays). What if I want to do the opposite: break a tuple up and
append the values to given arrays:
map(append, arrays, tupl)
except there is no unbound append() (List.append() does not exist,
right?).
Without append(), I am forced to write a (slow) explicit loop:
for (a, v) in zip(arrays, tupl):
a.append(v)
I assume using an index variable instead wouldn't be much faster.
Is there a better solution?
Thanks,
igor
Dec 15 '07
11 9056
Rich Harkins wrote:
ig************@ gmail.com wrote:
>Given a bunch of arrays, if I want to create tuples, there is zip(arrays). What if I want to do the opposite: break a tuple up and append the values to given arrays: map(append, arrays, tupl) except there is no unbound append() (List.append() does not exist, right?).
list.append does exist (try the lower-case flavor).
>Without append(), I am forced to write a (slow) explicit loop: for (a, v) in zip(arrays, tupl): a.append(v)
Except that isn't technically the opposite of zip. The opposite would
be a tuple of single-dimensional tuples:
def unzip(zipped):
"""
Given a sequence of size-sized sequences, produce a tuple of tuples
that represent each index within the zipped object.
Example:
>>zipped = zip((1, 2, 3), (4, 5, 6))
>>zipped
[(1, 4), (2, 5), (3, 6)]
>>unzip(zippe d)
((1, 2, 3), (4, 5, 6))
"""
if len(zipped) < 1:
raise ValueError, 'At least one item is required for unzip.'
indices = range(len(zippe d[0]))
return tuple(tuple(pai r[index] for pair in zipped)
for index in indices)
This is probably not the most efficient hunk of code for this but this
would seem to be the correct behavior for the opposite of zip and it
should scale well.
Modifying the above with list.extend would produce a variant closer to
what I think you're asking for:
def unzip_extend(de sts, zipped):
"""
Appends the unzip versions of zipped into dests. This avoids an
unnecessary allocation.
Example:
>>zipped = zip((1, 2, 3), (4, 5, 6))
>>zipped
[(1, 4), (2, 5), (3, 6)]
>>dests = [[], []]
>>unzip_extend( dests, zipped)
>>dests
[[1, 2, 3], [4, 5, 6]]
"""
if len(zipped) < 1:
raise ValueError, 'At least one item is required for unzip.'
for index in range(len(zippe d[0])):
dests[index].extend(pair[index] for pair in zipped)
This should perform pretty well, as extend with a comprehension is
pretty fast. Not that it's truly meaningful, here's timeit on my 2GHz
laptop:
bash-3.1$ python -m timeit -s 'import unzip; zipped=zip(rang e(1024),
range(1024))' 'unzip.unzip_ex tend([[], []], zipped)'
1000 loops, best of 3: 510 usec per loop
By comparison, here's the unzip() version above:
bash-3.1$ python -m timeit -s 'import unzip; zipped=zip(rang e(1024),
range(1024))' 'unzip.unzip(zi pped)'
1000 loops, best of 3: 504 usec per loop
Rich
As Paddy wrote, zip is its own unzip:
>>zipped = zip((1, 2, 3), (4, 5, 6)) zipped
[(1, 4), (2, 5), (3, 6)]
>>unzipped = zip(*zipped) unzipped
[(1, 2, 3), (4, 5, 6)]
Neat and completely confusing, huh? :-)
<http://paddy3118.blogs pot.com/2007/02/unzip-un-needed-in-python.html>
--
Matt Nordhoff wrote:
[snip]
>
As Paddy wrote, zip is its own unzip:
>>>zipped = zip((1, 2, 3), (4, 5, 6)) zipped
[(1, 4), (2, 5), (3, 6)]
>>>unzipped = zip(*zipped) unzipped
[(1, 2, 3), (4, 5, 6)]
Neat and completely confusing, huh? :-)
<http://paddy3118.blogs pot.com/2007/02/unzip-un-needed-in-python.html>
I hadn't thought about zip() being symmetrical like that. Very cool...
Rich This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ray Tomes |
last post by:
Hi all
Many thanks to those that answered my questions about whitespace and ord()
being reverse of chr(). As well as the 2 things I asked about I learned
about 5 other useful things.
This I am trying to flip an array around so that the "subscripts" happen
in the opposite order and reading the docs I thought that zip() did this.
So I tried it like this:
|
by: Tertius |
last post by:
Is there a method to create a dict from a list of keys and a list of
values ?
TIA
Tertius
|
by: Will Stuyvesant |
last post by:
I am uploading a .zip file to a Python CGI program, using a form on
a HTML page with
<input name="yourfile" type="file">...
In the Python CGI program I do:
import cgi
fStorage = cgi.FieldStorage()
zipdata = fStorage.value
|
by: Frostillicus |
last post by:
I'm trying to get an ASP to return a zip file to the remote browser from an
Image (BLOB) field in SQL Server 2000 but Internet Explorer keeps saying:
Cannot open C:\Documents and Settings\Frostillicus\Local Settings\Temporary
Internet Files\Content.IE5\U7GXENGF\file.zip
The URL to open the zip file is like this: doc_view.asp?id=1&ver=2
....where id and ver represent the zip file's version in the database. The
code I've pieced...
|
by: Axel Foley |
last post by:
I used some of the excellent resources from DITHERING.COM for help in my
groveling newbie attempts to cough up working form validation....
I cut and pasted bits of code to check USA ZIP codes and CANADIAN POSTAL
codes, and merged them into one function that I called validCode. The
<form> tag has an onSubmit call to a general form-checker that works fine to
make sure all fields are filled. But within the form is a ZIP/POSTAL CODE
field,...
| |
by: Steven Bethard |
last post by:
> >>> aList =
> >>> it = iter(aList)
> >>> zip(it, it)
>
> That behavior is currently an accident.
>http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1121416
|
by: DataSmash |
last post by:
I need to unzip all zip file(s) in the current directory
into their own subdirectories. The zip file name(s) always
start with the string "usa" and end with ".zip".
The code below will make the subdirectory, move the zip
file into the subdirectory, but unzips the contents into the
root (current) directory. I want the contents of the zip file
unloaded into the newly created subdirectory where the zip file is.
Any ideas?
Thanks.
|
by: =?Utf-8?B?Q2hyaXMgRmluaw==?= |
last post by:
I am trying to make a minor modification to the code below and need some
assistance. Currently this code is using the java.util, java.util.zip, and
java.io assemblies from the vjslib.dll assembly. This code works fine by
taking file(s) from
disk and creating a zip file to disk. I need to modify this code to read a
file from a byte array and then output the zip file to a byte array (all done
in memory instead of disk). The reason for...
|
by: sandhyabhavani |
last post by:
This article is used to zip a file or directory using vb.net. The classes and method to zip a file is availale in java.io, java.util, java.util.zip class library.To import these you have to add a reference vsjlib Library in .net component.
.NET Classes used :
Imports System.IO
Imports java.io
Imports java.util
Imports java.util.zip
|
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.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
| |
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |