Here is a question about list comprehensions [lc]. The
question is dumb because I can do without [lc]; but I am
posing the question because I am curious.
This: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result = [] for d in data:
.... for w in d:
.... result.append(w ) print result
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
puts all the words in a list, like I want.
How to do this with [lc] instead of for-loops?
I tried funnies like [[w for w in L] for L in data],
that is correct syntax, but you'd never guess.
I know, silly! No need for [lc]! So there's my
question. I am sure a one-liner using [lc] will be very
enlightening. Like studying LISP.
--
I wish there was a knob on the TV to turn up the intelligence.
There's a knob called `brightness', but it doesn't work.
-- Gallagher 35 2044
Will Stuyvesant wrote: I tried funnies like [[w for w in L] for L in data], that is correct syntax, but you'd never guess.
That is absolutely correct. It's not a funnie at all. If you find it odd
it's only because you are not used to list comprehensiones .
In that case you might be more comfortable with:
data = [['foo','bar','ba z'],['my','your'],['holy','grail']]
result = []
for l in data:
result += l
--
hilsen/regards Max M, Denmark http://www.mxm.dk/
IT's Mad Science
Will Stuyvesant wrote: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result = [] for d in data: ... for w in d: ... result.append(w ) print result ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
Take advantage of the fact that you can have more than one 'for' in a
list comprehension: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] [item for item_list in data for item in item_list]
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
Steve
Will Stuyvesant wrote: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result = [] for d in data: ... for w in d: ... result.append(w ) print result ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
puts all the words in a list, like I want.
How to do this with [lc] instead of for-loops? data = [['foo','bar','ba z'],['my','your'],['holy','grail']] [w for d in data for w in d]
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
See how the for expressions in the list comprehension exactly match your
nested for loops? That's all there is to it.
Peter
>>> data = [['foo','bar','ba z'],['my','your'],['holy','grail']] [e for l in data for e in l]
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
--
Regards,
Diez B. Roggisch
Max M wrote: I tried funnies like [[w for w in L] for L in data], that is correct syntax, but you'd never guess. That is absolutely correct. It's not a funnie at all. If you find it odd it's only because you are not used to list comprehensiones .
well, syntactically correct or not, it doesn't do what he want...
In that case you might be more comfortable with:
data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result = [] for l in data: result += l
how about (slightly evil):
result = []; map(result.exte nd, data)
</F>
Fredrik Lundh wrote: Max M wrote:
I tried funnies like [[w for w in L] for L in data],
That is absolutely correct. It's not a funnie at all.
well, syntactically correct or not, it doesn't do what he want...
Doh! *I* might not be used to list comprehensions then... You are right.
That example could have been expressed more clearly as:
result = data
;-)
--
hilsen/regards Max M, Denmark http://www.mxm.dk/
IT's Mad Science
I guess the simplest to do it is like this: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result=[w for d in data for w in d] result
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
I guess the simplest way to do it is like this: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result=[w for d in data for w in d] result
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
Here is one for arbitrary depth:
def unroll(ary):
unrolled = []
for item in ary:
# add test for your favorite sequence type
if ( type(item) == types.ListType or \
type(item) == types.TupleType \
):
unrolled.extend (unroll(item))
else:
unrolled.append (item)
return unrolled unroll([[1, 2, 3], ('fred', 'barney', ['wilma', 'betty']), 'dino'])
[1, 2, 3, 'fred', 'barney', 'wilma', 'betty', 'dino']
On Monday 13 December 2004 12:51 pm, Will Stuyvesant wrote: Here is a question about list comprehensions [lc]. The question is dumb because I can do without [lc]; but I am posing the question because I am curious.
This: data = [['foo','bar','ba z'],['my','your'],['holy','grail']] result = [] for d in data: ... for w in d: ... result.append(w ) print result
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
puts all the words in a list, like I want.
How to do this with [lc] instead of for-loops?
I tried funnies like [[w for w in L] for L in data], that is correct syntax, but you'd never guess.
I know, silly! No need for [lc]! So there's my question. I am sure a one-liner using [lc] will be very enlightening. Like studying LISP.
--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
611 Charles E. Young Dr. S.
MBI 205, UCLA 951570
Los Angeles CA 90095-1570 http://www.jamesstroud.com/ This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Elaine Jackson |
last post by:
List comprehensions don't work the way you intuitively expect them to work. I
realize many people have no intuitions about how list comprehensions 'should'
work, so if you recognize yourself in this description, feel free to go back to
whatever you were doing before. If you're still here, though, I invite you to
consider the following definition:
partitions = lambda n: ]++x for x in partitions(n-k) for k in
range(1,n)]
As defined...
|
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: Neuruss |
last post by:
I have a doubt regarding list comprehensions:
According to Mark Lutz in his book Learning Pyhon:
"...there is currently a substantial performance advantage to the
extra complexity in this case: based on tests run under Python 2.2,
map calls are roughly twice as fast as equivalent for loops, and list
comprehensions are usually very slightly faster than map. This speed
difference owes to the fact that map and list comprehensions run at C...
|
by: Alan McIntyre |
last post by:
Hi all,
I have a list of items that has contiguous repetitions of values, but
the number and location of the repetitions is not important, so I just
need to strip them out. For example, if my original list is
, I want to end up with .
Here is the way I'm doing this now:
def straightforward_collapse(myList):
|
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: Steven Bethard |
last post by:
Tom Anderson <twic@urchin.earth.li> wrote:
> Sounds good. More generally, i'd be more than happy to get rid of list
> comprehensions, letting people use list(genexp) instead. That would
> obviously be a Py3k thing, though.
Alex Martelli wrote:
> I fully agree, but the BDFL has already (tentatively, I hope)
> Pronounced that the form will stay in Py3K as syntax sugar for
> list(...). I find that to be a truly hateful prospect, but...
|
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: Lonnie Princehouse |
last post by:
List comprehensions appear to store their temporary result in a
variable named "_" (or presumably "_", "_" etc for nested
comprehensions)
In other words, there are variables being put into the namespace with
illegal names (names can't contain brackets). Can't someone come up
with a better hack than this? How about using "_1", "_2", etc, or
actually making "_" a list of lists and using the real first, second,
third elements? This is...
|
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...
|
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: 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...
|
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: 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...
| |