f



list of lists of lists ....

Hi,

I have a list of data (type A)
my list can includes element of type A or a lists,
these list can includes element of type A or a lists, and so on ...

is there a simple way to obtain a single list of all the elemets
of type A ?

thanks

yomgui
0
not2608 (5)
7/28/2006 6:19:48 PM
comp.lang.python 77058 articles. 6 followers. Post Follow

6 Replies
2179 Views

Similar Articles

[PageSpeed] 57

I forgot the most important, I am looking for a non recursive method.

thanks

yomgui

yomgui wrote:
> 
> Hi,
> 
> I have a list of data (type A)
> my list can includes element of type A or a lists,
> these list can includes element of type A or a lists, and so on ...
> 
> is there a simple way to obtain a single list of all the elemets
> of type A ?
> 
> thanks
> 
> yomgui
0
not2608 (5)
7/28/2006 6:27:29 PM
recursion.
def get_As(L):
    res = []
    for elem in L:
        if isinstance(elem, A):
            res.append(elem)
        elif isinstance(elem, list):
            res += get_As(elem)
    return res

i also have a Tree class in my rc:
http://home.comcast.net/~faulkner612/programming/python/pythonrc.py

yomgui wrote:
> Hi,
>
> I have a list of data (type A)
> my list can includes element of type A or a lists,
> these list can includes element of type A or a lists, and so on ...
>
> is there a simple way to obtain a single list of all the elemets
> of type A ?
> 
> thanks
> 
> yomgui

0
7/28/2006 6:32:10 PM
doh.
ok, so, recursion is just functional programming sugar for a loop.
def get_As(L):
    checking = [elem for elem in L if isinstance(elem, list)]    # the
equivalent of elem in recursion
    all_As = [elem for elem in L if isinstance(elem, A)]
    while checking:
        new_checking = []   # all lists in all lists in checking
        for sub_L in checking:
            for elem in sub_L:
                if isinstance(elem, A):
                    all_As.append(elem)
                elif isinstance(elem, list):
                    new_checking.append(elem)
        checking = new_checking
    return all_As


yomgui wrote:
> I forgot the most important, I am looking for a non recursive method.
>
> thanks
>
> yomgui
>
> yomgui wrote:
> >
> > Hi,
> >
> > I have a list of data (type A)
> > my list can includes element of type A or a lists,
> > these list can includes element of type A or a lists, and so on ...
> >
> > is there a simple way to obtain a single list of all the elemets
> > of type A ?
> > 
> > thanks
> > 
> > yomgui

0
7/28/2006 6:46:58 PM
faulkner wrote:
> ok, so, recursion is just functional programming sugar for a loop.

And a loop is a procedural programming sugar for tail recursion. 8-)

Cheers,
mk
-- 
 . o .       >>  http://joker.linuxstuff.pl  <<
 . . o   It's easier to get forgiveness for being wrong
 o o o   than forgiveness for being right.
0
ruby20 (27)
7/28/2006 6:54:55 PM
You can use this, fast, gives a tuple:

from Tkinter import _flatten as flatten

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

The xflatten/flatten version I sometimes use, maybe I can put something
similar in the cookbook, but it can be improved a lot (and isrecursive
is too much fragile):

from pprint import isrecursive

def xflatten(seq, tuplestoo=True, safe=True):
    """xflatten(seq, tuplestoo=True, safe=False): Flattens a sequence,
      giving an iterabile. If tupledtoo=True then it flattens tuples
too.
    safe=True enables the recursive reference check, do not use it for
too
      much nested structures. Examples (iterators):
    xflatten( "a" ) ==> ['a']
    xflatten( [] ) ==> []
    xflatten( [[1,[2,[],"a"]]] ) ==> [1,2,'a']
    xflatten( [()] ) ==> []
    xflatten( ([[1,[2,[],"a", ()]]],) ) ==> [1, 2, 'a']
    xflatten( (12, 34, (11,)) ) ==> (12, 34, 11)
    xflatten( (12, 34, (11,)), False ) ==> [(12, 34, (11,))]
    Notes on speed:
      tuple(xflatten()) is much slower than list(xflatten()).
      tuplestoo=False makes this function faster.
      safe=True makes this function slower."""
    # Modified from: http://google.com/groups?th=957cfbd2e46ac001
    if safe and isrecursive(seq):
        raise TypeError, "given structure contains a recursive
reference."
    if tuplestoo:
        if seq.__class__ not in (list, tuple):
            yield seq
        else:
            stack = [iter(seq)]
            while stack:
                for item in stack[-1]:
                    if item.__class__ in (list, tuple):
                        stack.append(iter(item))
                        break
                    yield item
                else:
                    stack.pop()
    else:
        if not seq.__class__ is list:
            yield seq
        else:
            stack = [iter(seq)]
            while stack:
                for item in stack[-1]:
                    if item.__class__ is list:
                        stack.append(iter(item))
                        break
                    yield item
                else:
                    stack.pop()


def flatten(seq, tuplestoo=True, safe=True):
    # Do not use tuple(xflatten(...)), it's slow.
    return list(xflatten(seq, tuplestoo, safe))

Bye,
bearophile

0
7/28/2006 7:01:29 PM
thanks for all your answers

yomgui

yomgui wrote:
> 
> Hi,
> 
> I have a list of data (type A)
> my list can includes element of type A or a lists,
> these list can includes element of type A or a lists, and so on ...
> 
> is there a simple way to obtain a single list of all the elemets
> of type A ?
> 
> thanks
> 
> yomgui
0
not2608 (5)
7/31/2006 7:28:28 PM
Reply:

Similar Artilces:

List of lists of lists of lists...
I would like to have a list of lists N times deep, and my solution is (in pseudocode): def deep(x): a=[x] return a mylist=[] for N: mylist=deep(mylist) Is there a more elegant way to do it? The maine idea is: from a list having the numbre of steps along N dimensions, generate a list with an item at each possible point. Example 1: N=2 list=[2,3] result=[[1,2],[1,2],[1,2]] Example 2: N=3 list=[3,1,2] result=[[[1,2,3]],[[1,2,3]]] -- Ángel Gutiérrez Rodríguez - agr@fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiat...

Sort a List, in a List of Lists of Lists
Dear Mathgroup, I have a lsit of Lists of Lists: {{{1,2},{2,1},{1,1}},{{1,1},{1,1},{1,2}},{{2,1},{2,2},{1,2}},{{2,2},{1,2},{2,2}},{{1,1},{2,1},{1,2}},{{1,2},{2,2},{2,2}}} I would like to sort the elements in the lowest level of brackets to give {{{1, 2}, {1, 2}, {1, 1}}, {{1, 1}, {1, 1}, {1, 2}}, {{1, 2}, {2, 2}, {1, 2}}, {{2, 2}, {1, 2}, {2, 2}}, {{1, 1}, {1, 2}, {1, 2}}, {{1, 2}, {2, 2}, {2, 2}}} i.e retaining the same structure with the paired elements in the original order. I can't seem to get the syntax right to do this apart from the obvious {{Sort[{1,...

Re: Sort a List, in a List of Lists of Lists
On 11/13/10 at 12:59 AM, leigh.pascoe@inserm.fr wrote: >I have a lsit of Lists of Lists: >{{{1,2},{2,1},{1,1}},{{1,1},{1,1},{1,2}},{{2,1},{2,2},{1,2}},{{2,2}, >{1,2},{2,2}},{{1,1},{2,1},{1,2}},{{1,2},{2, 2},{2,2}}} >I would like to sort the elements in the lowest level of brackets to >give >{{{1, 2}, {1, 2}, {1, 1}}, {{1, 1}, {1, 1}, {1, 2}}, {{1, 2}, {2, >2}, {1, 2}}, {{2, 2}, {1, 2}, {2, 2}}, {{1, 1}, {1, 2}, {1, 2}}, >{{1, 2}, {2, 2}, {2, 2}}} >i.e retaining the same structure with the paired elements in the >original order. I can't seem...

List of Atom or List of List??
how can detect some element of list is list o Atom?? for example when i try head (head p1) where p1=[[1,2],2] return 1 but when try head (head p1) where p1=[1,2] it returns Error plz help me..it my project and i have just 2 hours..:( i want to replace on Atom by another in list..for example: replace 1 2 [1,2] => [2,2] but sometime i have replace 1 2 [[1,2],2]=>[[2,2],2] i want to detect if first element of list is list then recurcively call head on that element.. is there any solutions?? On 8 Apr 2007 02:46:25 -0700, kheirandish.amin@gmail.com wrote: >how can detect some element of list is list o Atom?? (list? 42) --> #f (list? '(42 37)) --> #t Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ in Haskell plz, not Scheme In article <1176025585.229021.233310@w1g2000hsg.googlegroups.com>, <kheirandish.amin@gmail.com> wrote: > how can detect some element of list is list o Atom?? What is an atom? That is term is not commonly used with Haskell. > for example > when i try head (head p1) where p1=[[1,2],2] return 1 > but when try head (head p1) where p1=[1,2] it returns Error It doesn't _return_ an error, but your expression fails to type-check. Haskell's lists are homogeneous, i.e. all the elements are of the same type. So either _all_ elements are lists (in which case the list of lists has type [[a]] for some type a), or none of them are (in which case the list has type [b] for some type ...

Extracting a List from a List of lists
Hi, I have an ArrayList of ArrayLists. I want to extract all the lists, but I dont know how many ArrayLists will be in the ArrayList. I know I can do it if i know how many lists are there using the ArrayList get() method. this is how i'm doing it List<String> list1 = new ArrayList<String>(); list1 = res.get(0); List<String> list1 = new ArrayList<String>(); list2 = res.get(1); List<String> list1 = new ArrayList<String>(); list3 = res.get(2); But if theres only two lists in the list i get a NullPointerException Is there any way i can loop through the l...

convert list of lists to list
Is there a way to convert list_of_listsA to list_of_listsB, where one list in listof lists A is one element of listB? list_of_listsA: [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['koe'], ['arm*', '*', '*(haar)'], ['groei*', '*', '*', '*', '*']] listB: ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * *'] Thankx! antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one >...

How to have a list of lists (or array of lists)
Hi, I want to have many lists, such as list0, list1, list2, ..., each one holding different number of items. Is there something like list[0] list[1] list[2] so that I can iterate through this list of lists? Thanks! bahoo On Apr 3, 7:12 pm, "bahoo" <b83503...@yahoo.com> wrote: > Hi, > > I want to have many lists, such as list0, list1, list2, ..., each one > holding different number of items. > Is there something like > list[0] > list[1] > list[2] > > so that I can iterate through this list of lists? > > Thanks! > bahoo listOfLists = [...

Copying a List to a List of Lists
Hi, I am having trouble with the following: I wish to have a list of lists of type Double called A. I then have a separate List of Doubles called B which i wish to add to A. I then want to be able to clear B and reuse it without clearing what I have added to A. Currently my code looks like: for(int i=0;i<seqLength;i++) { B.clear(); for(int j=i+1;j<seqLength;j++) { if(fourGameteTest(i,j)) { B.add(segPositions.get(j)); } } A.get(i).add(B); } However, it seems that due to, I guess the element held in A being a reference to the same pl...

List of a list
Hi, I'm very new to latex. I'm trying to make a list of a list, with: \begin{list}{} \item \begin{list}{} \item \end{list} \end{list} However, I'm getting the error: Runaway argument? ! Paragraph ended before \list was complete. <to be read again> \par l.2273 However, I can do a list of enumerates, but that's not what I want. Is this a clash in syntax? Is there a way to prevent this? Please help. Michael On 1 Nov 2004 00:19:43 -0800, Michael <dayzman@hotmail.com> wrote: > Hi, > I'm very new to latex. I'm trying to make a list ...

list*list
There must be a better way to multiply the elements of one list by another: a = [1,2,3] b = [1,2,3] c = [] for i in range(len(a)): c.append(a[i]*b[i]) a = c print a [1, 4, 9] Perhaps a list comprehension or is this better addressed by NumPy? Thanks, jab > There must be a better way to multiply the elements of one list by > another: > > a = [1,2,3] > b = [1,2,3] > c = [] > for i in range(len(a)): > c.append(a[i]*b[i]) > a = c > print a > [1, 4, 9] > > Perhaps a list comprehension or is this better addressed by NumPy? First of all: it's ...

List of lists
So you can create listoffigures tableofcontents and listoftables, but can you and if so how do you do the same thing for a list of numbered lists? Cheers Try the tocloft package: http://www.ctan.org/tex-archive/help/Catalogue/entries/tocloft.html On 21 Mar, 17:26, "Matt" <matthew.w.tur...@gmail.com> wrote: > Try the tocloft package: > > http://www.ctan.org/tex-archive/help/Catalogue/entries/tocloft.html That looks great, cheers. But I am having trouble using it. This is the code I am trying, just lifted from the instructions: \newcommand{\listanswername}{List o...

lists of lists
I'm using C++ and I'm trying to create a list of a list and it won't let me create an iterator for it. if I do a list of an int, everything is fine. my syntax is list<list<string> > some_list; and my iterator would be someting like list<list>::Iterator blah; or maybe list<list<string> >::Iterator blah; ?? neither work, ofcourse. basicaly I'm trying to parse a text file, each line is token that contains tokens and I have a function that takes a string and returns the list of the tokens. so I have my the parent list to contain lists to t...

Lists of lists
I've written a simple forum. The posts are lists of lists of lists... Each new list steps out the left margin. What happens is that after so many replies the lists get pushed too far right. I'd like to reset the list margin back to the beginning. for ex: ul > ul>ul> ul > ul... { margin-left: original thread left position; ??? position: absolute; left 0; } For ex: http://earlymorningreport.com/test_zig_zag_lists.html I would think this would not be an uncommon request. How now can we do this (other than that)? Jeff In article <jpom3b...

List of lists
How do I extract a list of lists from a user defined function and print the results as strings for each list? On Fri, 27 Jun 2003 01:44:42 GMT, Mike wrote: > How do I extract a list of lists from a user defined function Depends how that function is returning its values. The most obvious, and simplest way to do what you describe, is to have the function return a list of lists, as its return value. If you mean something else, you'll have to be more descriptive of what you actually want to do. > and print the results as strings for each list? The 'repr()' method of any o...

list or not a list?
Hello, I was a bit astonished using such tcl code: % set list "Abbruch der Aktion \" ##ACTION \" !" Abbruch der Aktion " ##ACTION " ! % llength $list 5 % llength [split $list] 7 % % set idx 0 0 % foreach element $list {puts "element($idx) = '$element'"; incr idx} element(0) = 'Abbruch' element(1) = 'der' element(2) = 'Aktion' element(3) = ' ##ACTION ' element(4) = '!' % % set idx 0 0 % foreach element [split $list] {puts "ele...

Lists from Lists
Can anyone tell me how can I make a list from all the first elements of the following pairs? l:=[[1,2],[3,4],[5,6],[7,8]] ; to get, m:=[1,3,5,7]; Thanks, Tony Connell "Tony Connell" <a.connell@galileo.karoo.co.uk> wrote in message news:vfk59prj7bp0fb@corp.supernews.com... > Can anyone tell me how can I make a list from all the first elements of the > following pairs? > > l:=[[1,2],[3,4],[5,6],[7,8]] ; > > to get, > > m:=[1,3,5,7]; > If you know the length of the list you could do like this: > m:=[seq(l[i][1], i=1..4)]; -Reidar Kind Tony Connell" <a.connell@galileo.karoo.co.uk> wrote: > Can anyone tell me how can I make a list from all the first elements of > the following pairs? > l:=[[1,2],[3,4],[5,6],[7,8]] ; map2(op, 1, l); "Tony Connell" <a.connell@galileo.karoo.co.uk> wrote in message news:vfk59prj7bp0fb@corp.supernews.com... > Can anyone tell me how can I make a list from all the first elements of the > following pairs? > > l:=[[1,2],[3,4],[5,6],[7,8]] ; > > to get, > > m:=[1,3,5,7]; m:=l[1..-1,1]; Alec Mihailovs http://webpages.shepherd.edu/amihailo/ "Reidar Kind" <s989788@stud.nhh.no> wrote in message news:A%oKa.13616$KF1.276672@amstwist00... > > "Tony Connell" <a.connell@galileo.karoo.co.uk> wrote in message > news:vfk59prj7bp0fb@cor...

List of lists...
I would like to add a List environment with an accompanying list of lists included at the front of the document. Basically, a List is like a table or a figure. However, I want to be able to refer to a bulleted list. I am using gatech-thesis.cls (which is based on report.cls). I went through report.cls, and copied everything having to do with figures into gatech-thesis.cls (just after it includes report.cls) and changed everything that said figure to list. Then, I went through gatech-thesis.cls, and copied everything having to do with figures, changing everything that said figure to list.....

When is a List not a List?
g[x_, n_] := x^n FullForm[Table[g[x, n], {n, 1, 2}]] FullForm[{g[x, 1], g[x, 2]}] Plot[{g[x, 1], g[x, 2]}, {x, 0, 1}, PlotStyle -> {Red, Blue}] Plot[Table[g[x, n], {n, 1, 2}], {x, 0, 1}, PlotStyle -> {Red, Blue}] The FullForm[]s are identical. One Plot[] has red and blue curves; the other has two blue curves. Quirky! AES wrote: > g[x_, n_] := x^n > FullForm[Table[g[x, n], {n, 1, 2}]] > FullForm[{g[x, 1], g[x, 2]}] > Plot[{g[x, 1], g[x, 2]}, {x, 0, 1}, PlotStyle -> {Red, Blue}] > Plot[Table[g[x, n], {n, 1, 2}], {x, 0, 1}, PlotStyle -> {Red, Blue}] > > The FullForm[]s are identical. One Plot[] has red and blue curves; the > other has two blue curves. > > Quirky! Not at all, as it has already been explained many times in this very newsgroup (notwithstanding the online help that contains some examples illustrating this point). Plot does not evaluate immediately its arguments because it has the attribute HoldAll: Attributes[Plot] {HoldAll, Protected} So, having the attribute HoldHold, what Plot "sees" in first instance the unevaluated expression Table[g[x, n], {n, 1, 2}], which stands for only *one* function. Thus the choice of colors is just for one function/expression, not for the list of functions that will be returned after evaluation of the first argument. To force the evaluation of the first argument before doing anythin...

Lists of list
Hi All I am having problem with delete line if its belong to another one , example ['0132442\n', '13\n', '24\n'] the 2nd and 3rd are already in the first line , how can do this !!! Thanks Mohammed Altaj wrote: > Hi All > > I am having problem with delete line if its belong to another one , example I think, you mean to remove all lines that are substrings of another line. l = ['0132442\n', '13\n', '24\n'] l = [e.strip() for e in l] i = 0 while True: try: for j in range(len(l)): if i == j: continue if l[j]...

Breaking Python list into set-length list of lists
Hey everyone-- I'm pretty new to Python, & I need to do something that's incredibly simple, but combing my Python Cookbook & googling hasn't helped me out too much yet, and my brain is very, very tired & flaccid @ the moment.... I have a list of objects, simply called "list". I need to break it into an array (list of lists) wherein each sublist is the length of the variable "items_per_page". So array[0] would go from array[0][0] to array[0][items_per_page], then bump up to array[1][0] - array[1] [items_per_page], until all the items in the origin...

common elements between list of lists and lists
Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = ['1', '2', '3'] for j in list4: for k in list5: if j[0] == k: print j[1] Result: a I would like to do the same thing starting with following lists, where the numbers in list 5 are without ''. Is there a way to convert integers in a list to integers in '' ? This is based on a...

TSV files as a list of list of lists?
I am loading a few GPS data files as TSV (tab separated). What I would like to do is make the loading of files a bit more dynamic, so I make a list of the file contents. But since the file contents is a list in itself, I get in trouble when I want to manipulate the data. It just takes too long. First, here is how I do it for one file only: GPS1 = Import["F:\\Documents\\Jobb\\SLU\\xyuvw\\GPS.txt", "TSV"] (* Remove column-headers *) GPS1 = Drop[GPS1, 1] (* Make sure row 1 of column 2 or 3 doesn't contain spaces so \ they can be interpreted as numbers (I use swe...

Listings package / List of Listings / Layout
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi - I am trying to get the 'List of Listings' to look like the 'List of Figures' and 'List of Tables' but I don't know how. Both the LOF and LOT (inside the files .lof and .lot) use \addvspace {10\p@} in between the entries for each chapter, but the LOL (in file ..lol) does not do that, 'messing up' the design I want. I know this is a pretty minor thing and not really noticable but nice to have if it works. I'll live without a solution, but if anybody has something for me, it's appreciated. Tha...

Converting a list of lists to a single list
I think that itertools may be able to do what I want but I have not been able to figure out how. I want to convert an arbitrary number of lists with an arbitrary number of elements in each list into a single list as follows. Say I have three lists: [[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]] I would like to convert those to a single list that looks like this: [A0,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2,A1,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2,A2,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2] An easier way to visualize the pattern I want is as a tree. A0 B0 C0 C1 C2 B1 C0 C1 C2 B2 C0 C1 C2 A1 B0 C0 C1 C2 B1 C0 C1 C2 B2 C0 C1 C2 A2 B0 C0 C1 C2 B1 C0 C1 C2 B2 C0 C1 C2 El 23/07/13 23:52, steve@divillo.com escribi�: > [[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]] Hi, I think you are looking for itertools.chain, or in this case, itertools.chain.from_iterable: In [1]: x = [['A0','A1','A2'], ['B0','B1','B2'], ['C0','C1','C2']] In [2]: import itertools In [3]: [ y for y in itertools.chain.from_iterable(x)] Out[3]: ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2'] HTH : On 23 July 2013 17:52, <steve@divillo.com> wrote: > > Say I have three lists: > > [[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]] > > I w...

Web resources about - list of lists of lists .... - comp.lang.python

Global Rich List
Didn't make it onto the yearly roll call of the mega-wealthy? Why not find out where you'd actually sit in comparison to the rest of the world? ...

Watch List News
Livermore air conditioning repair and maintenance is now being offered with a discount from Big Bear Heating & Air. A new diagnostic and Freon ...

List of districts of Seoul - Wikipedia, the free encyclopedia
The Gu of Seoul are the twenty-five gu ("districts"; 구; 區 ) comprising Seoul , South Korea . The gu vary greatly in area (from 10 to 47 km²) ...

Carlton's list worse than Essendon's: David Parkin
Coaching great David Parkin believes Carlton's 2016 AFL list is even weaker than that of an Essendon side missing a dozen banned stars, predicting ...

Large-scale brand loyalty survey shows Apple tops the list in laptops, tablets and smartphones
Brand loyalty consultancy Brand Keys says that Apple has topped the lists in three of the categories in which it competes: laptops, tablets and ...

Obama outlines his wish list for Supreme Court nominee
The president pens a guest post on SCOTUSblog

2016 NFL Combine: TV schedule, how to watch online, list of players
With the 2015 NFL season in the rear-view, we're officially into draft season and the first stop is the NFL combine in Indianapolis. It all begins ...

The Republican war on poor people's grocery lists continues
... steaks and lobsters and anything else dubbed a luxury item. When a similar bill was being debated in Missouri last year, Jeanine Grant Lister ...

Costume Designers Guild Awards: ‘Mad Max’, ‘Danish Girl’ & ‘Beasts Of No Nation’ Take Film Nods – Winners ...
Mad Max: Fury Road , The Danish Girl and Beasts of No Nation took the film prizes at the 18th annual Costume Designers Guild Awards, which were ...

Testing company CHPT to list on Taiwan OTC
... which specializes in high-end IC testing solutions such as load boards for final testing and probe cards for wafer probing, will be listed on ...

Resources last updated: 2/25/2016 8:14:26 PM