473,747 Members | 3,002 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recursive list comprehension

Hi all.

I have a list that looks like [['N', 'F'], ['E'], ['D']]
I try to make it flat one: ['N', 'F', 'E', 'D']

How can I archieve such an effect with list comprehension?
Two cycles did the job, but that way did not look pythonic..

I tried
print [x for x in y for y in c_vars]
and got NameError: name 'y' is not defined.

--
Timothy Babytch
Jul 18 '05 #1
21 2384
Timothy Babytch wrote:
Hi all.

I have a list that looks like [['N', 'F'], ['E'], ['D']]
I try to make it flat one: ['N', 'F', 'E', 'D']

How can I archieve such an effect with list comprehension?
Two cycles did the job, but that way did not look pythonic..

I tried
print [x for x in y for y in c_vars]
and got NameError: name 'y' is not defined.


The order of the for expressions is as it would be for nested loops:
items = [['N', 'F'], ['E'], ['D']]
[y for x in items for y in x] ['N', 'F', 'E', 'D']

I would still prefer a for loop because it spares you from iterating over
the sublist items in python:
data = []
for sub in [['N', 'F'], ['E'], ['D']]: .... data.extend(sub )
.... data

['N', 'F', 'E', 'D']

Peter

Jul 18 '05 #2
Peter Otten wrote:
The order of the for expressions is as it would be for nested loops:
items = [['N', 'F'], ['E'], ['D']]
[y for x in items for y in x]
I would still prefer a for loop because it spares you from iterating over
the sublist items in python:

data = []
for sub in [['N', 'F'], ['E'], ['D']]:


... data.extend(sub )
...


Thanks. Both tips were helpful.

--
Timothy Babytch
Jul 18 '05 #3
On Monday 06 Dec 2004 09:26, Timothy Babytch wrote:
Hi all.

I have a list that looks like [['N', 'F'], ['E'], ['D']]
I try to make it flat one: ['N', 'F', 'E', 'D']

How can I archieve such an effect with list comprehension?
Two cycles did the job, but that way did not look pythonic..

I tried
print [x for x in y for y in c_vars]
and got NameError: name 'y' is not defined.

--
Timothy Babytch


Hi,

I think you do it with a generator like this:

def flatten(nested) :
for sublist in nested:
for element in sublist:
yield element

n=[['N', 'F'], ['E'], ['D']]
output=[]

for value in flatten(n):
output.append(v alue)

print output

Have a merry Christmas

Peter Nuttall
Jul 18 '05 #4
Peter Nuttall wrote:
I think you do it with a generator like this:

def flatten(nested) :
for sublist in nested:
for element in sublist:
yield element

n=[['N', 'F'], ['E'], ['D']]
output=[]

for value in flatten(n):
output.append(v alue)

print output


I highly recommend learning about the stdlib module "itertools" (I only really
looked into it recently). The above can be done in 3 lines (counting imports):

from itertools import chain
n = [['N', 'F'], ['E'], ['D']]
print [chain(*n)]

Documentation:
http://www.python.org/doc/2.3.4/lib/...functions.html

Cheers,
Nick.
Jul 18 '05 #5
Nick Coghlan wrote:
from*itertools* import*chain
n*=*[['N',*'F'],*['E'],*['D']]
print*[chain(*n)]


However, [generator] is not the same as list(generator) :
from itertools import chain
n = [['N', 'F'], ['E'], ['D']]
print [chain(*n)] [<itertools.chai n object at 0x402ac60c>] print list(chain(*n)) ['N', 'F', 'E', 'D']

And with the star operator you are foregoing some laziness, usually an
important selling point for the iterator approach. Therefore:
n = [['N', 'F'], ['E'], ['D']]
lazyItems = (x for y in n for x in y)
lazyItems.next( ) 'N' list(lazyItems) ['F', 'E', 'D']


Of course this makes most sense when you want to keep the original n anyway
_and_ can be sure it will not be mutated while you are still drawing items
from the lazyItems generator.

Peter

Jul 18 '05 #6
Peter Otten wrote:
Nick Coghlan wrote:

from itertools import chain
n = [['N', 'F'], ['E'], ['D']]
print [chain(*n)]

However, [generator] is not the same as list(generator) :


Heh - good point. As you say, replacing with list() gives the intended answer.

With regards to laziness, my main point was that itertools is handy for
manipulating sequences, even if you aren't exploiting its capacity for lazy
evaluation.

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #7
Timothy Babytch wrote:
I have a list that looks like [['N', 'F'], ['E'], ['D']]
I try to make it flat one: ['N', 'F', 'E', 'D']

How can I archieve such an effect with list comprehension?
Two cycles did the job, but that way did not look pythonic..

I tried
print [x for x in y for y in c_vars]
and got NameError: name 'y' is not defined.


sum(c_vars, [])

--
Serhiy Storchaka
Jul 18 '05 #8
Serhiy Storchaka wrote:
sum([['N', 'F'], ['E'], ['D']], [])

['N', 'F', 'E', 'D']

THE BEST!

--
Timothy Babytch, PHP-dev Teamleader
Jul 18 '05 #9
Timothy Babytch wrote:
Serhiy Storchaka wrote:
>>>sum([['N', 'F'], ['E'], ['D']], [])

['N', 'F', 'E', 'D']

THE BEST!


Hmmm. Maybe, unless readability as in "self-documenting code"
is important to you...

Preceding the above with "flatten = sum" would perhaps be
an adequate improvement.

-Peter
Jul 18 '05 #10

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

Similar topics

23
40643
by: Fuzzyman | last post by:
Pythons internal 'pointers' system is certainly causing me a few headaches..... When I want to copy the contents of a variable I find it impossible to know whether I've copied the contents *or* just created a new pointer to the original value.... For example I wanted to initialize a list of empty lists.... a=, , , , ] I thought there has to be a *really* easy way of doing it - after a
35
2975
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':
1
4228
by: SimonVC | last post by:
Is there a way to do this as a list comprehension? >>> def recu(alist, blist=): .... if len(alist)==0: print blist .... for i in range(len(alist)): .... blist.append(alist.pop(i)) .... recu(alist, blist) .... alist.insert(i, blist.pop()) >>> recu(list("abc"))
10
5673
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. Not being a computer scientist, I find recursive functions to be frightening and unnatural. I'd appreciate if anyone can tell me the pythonic idiom to accomplish this. Thanks for your help,
7
567
by: Jon Slaughter | last post by:
#pragma once #include <vector> class empty_class { }; template <int _I, int _J, class _element, class _property> class RDES_T {
6
1983
by: jena | last post by:
hello, when i create list of lambdas: l=] then l() returns 'C', i think, it should be 'A' my workaround is to define helper class with __call__ method: class X: def __init__(self,s): self.s=s def __call__(self): return self.s.upper() l=]
18
460
by: a | last post by:
can someone tell me how to use them thanks
4
1812
by: Gregory Guthrie | last post by:
Sorry for a simple question- but I don't understand how to parse this use of a list comprehension. The "or" clauses are odd to me. It also seems like it is being overly clever (?) in using a lc expression as a for loop to drive the recursion. Thanks for any insight! Gregory
7
1503
by: cesco | last post by:
Hi, I have a dictionary of lists of tuples like in the following example: dict = {1: , 2: , 3: ] In this case I have three lists inside the dict but this number is known only at runtime. I have to write a function that considers all the possible combinations of tuples belonging to the different lists
0
8818
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
9522
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9354
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
9223
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
6067
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();...
0
4588
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...
0
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2771
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.