Newbie question:
I have been generally open to the proposal that list comprehensions
should replace 'map', but I ran into a need for something like
map(None,x,y)
when len(x)>len(y). I cannot it seems use 'zip' because I'll lose
info from x. How do I do this as a list comprehension? (Or,
more generally, what is the best way to do this without 'map'?)
Thanks,
Alan Isaac
Jul 27 '05
22 1900
Andrew Dalke wrote: Me: Could make it one line shorter with from itertools import chain, izip, repeat def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return [] return repeat(None) seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Peter Otten: that won't work because done_iter() is now no longer a generator. In effect you just say
seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], [])]
It does work - I tested it. The trick is that izip takes iter() of the terms passed into it. iter([]) -> an empty iterator and iter(repeat(Non e)) -> the repeat(None) itself.
Seems my description didn't convince you. So here's an example: from itertools import chain, izip, repeat def fillzip(*seqs):
.... def done_iter(done=[len(seqs)]):
.... done[0] -= 1
.... if not done[0]:
.... return []
.... return repeat(None)
.... seqs = [chain(seq, done_iter()) for seq in seqs]
.... return izip(*seqs)
.... list(fillzip(ra nge(6), range(3)))
[(0, 0), (1, 1), (2, 2)]
versus
map(None, range(6), range(3))
[(0, 0), (1, 1), (2, 2), (3, None), (4, None), (5, None)]
Now where's the typo?
'Course then the name should be changed.
My variable names where ill-chosen to begin with.
Peter
Scott David Daniels wrote: Can I play too?
Not unless you buy the expensive but good-looking c.l.py gaming license
which is only available trough me :)
How about: import itertools
def fillzip(*seqs): def Nones(countacti ve=[len(seqs)]): countactive[0] -= 1 while countactive[0]: yield None seqs = [itertools.chain (seq, Nones()) for seq in seqs] return itertools.izip( *seqs)
You may be introducing a lot of extra tests in the while loop with the
non-constant condition -- which in practice is fairly cheap, though.
I'm willing to take the performance hit for the introduction of sane
variable names alone...
Peter
Peter Otten wrote: Seems my description didn't convince you. So here's an example:
Got it. In my test case the longest element happened to be the last
one, which is why it didn't catch the problem.
Thanks.
Andrew da***@dalkescie ntific.com This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Guy Robinson |
last post by:
Hello,
Trying to change a string(x,y values) such as :
s = "114320,69808 114272,69920 113568,71600 113328,72272"
into (x,-y):
out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"
|
by: Moosebumps |
last post by:
Does anyone here find the list comprehension syntax awkward?
I like it because it is an expression rather than a series of statements,
but it is a little harder to maintain it seems.
e.g. you could do:
result =
for element in list:
if element == 'blah':
|
by: Mahesh Padmanabhan |
last post by:
Hi,
When list comprehension was added to the language, I had a lot of
trouble understanding it but now that I am familiar with it, I am not
sure how I programmed in Python without it.
Now I see that generator expressions have been added to the language
with 2.4 and I question the need for it. I know that it allows for lazy
evaluation which speeds things up for larger lists but why was it
necessary to add it instead of improving list...
|
by: Matt Gerrans |
last post by:
This is probably so easy that I'll be embarrassed by the answer. While
enhancing and refactoring some old code, I was just changing some map()s to
list comprehensions, but I couldn't see any easy way to change a zip() to a
list comprehension. Should I just let those sleeping dogs lie? (list
comprehensions seem more readable than map(), but if the list comprehension
that does the equivalent of zip() is less expressive than zip(), I'll...
|
by: Mike Meyer |
last post by:
Ok, we've added list comprehensions to the language, and seen that
they were good. We've added generator expressions to the language, and
seen that they were good as well.
I'm left a bit confused, though - when would I use a list comp instead
of a generator expression if I'm going to require 2.4 anyway?
Thanks,
<mike
--
| |
by: Steven Bethard |
last post by:
George Sakkis wrote:
> "Steven Bethard" <steven.bethard@gmail.com> wrote:
>> Dict comprehensions were recently rejected:
>> http://www.python.org/peps/pep-0274.html
>> The reason, of course, is that dict comprehensions don't gain you
>> much at all over the dict() constructor plus a generator expression,
>> e.g.:
>> dict((i, chr(65+i)) for i in range(4))
>
> Sure, but the same holds for list comprehensions: list(i*i for i in
|
by: Heiko Wundram |
last post by:
Hi all!
The following PEP tries to make the case for a slight unification of for
statement and list comprehension syntax.
Comments appreciated, including on the sample implementation.
===
PEP: xxx
Title: Unification of for-statement and list-comprehension syntax
|
by: bullockbefriending bard |
last post by:
Given:
class Z(object):
various defs, etc.
class ZList(list):
various defs, etc.
i would like to be able to replace
|
by: Pat |
last post by:
I have written chunks of Python code that look this:
new_array =
for a in array:
if not len( a ):
continue
new_array.append( a )
and...
|
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,...
|
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: 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,...
|
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: 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: 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...
| |