473,386 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Flatten a list/tuple and Call a function with tuples

Hi,

I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].

Another question is how do I pass a tuple or list of all the
aurgements of a function to the function. For example, I have all the
arguments of a function in a tuple a=(1,2,3). Then I want to pass each
item in the tuple to a function f so that I make a function call
f(1,2,3). In perl it is a given, but in python, I haven't figured out
a way to do it. (Maybe apply? but it is deprecated?)

Thanks,
cg

Jul 25 '07 #1
25 4055
On Jul 25, 9:50 am, beginner <zyzhu2...@gmail.comwrote:
Hi,

I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].

Another question is how do I pass a tuple or list of all the
aurgements of a function to the function. For example, I have all the
arguments of a function in a tuple a=(1,2,3). Then I want to pass each
item in the tuple to a function f so that I make a function call
f(1,2,3). In perl it is a given, but in python, I haven't figured out
a way to do it. (Maybe apply? but it is deprecated?)

Thanks,
cg
I'm not sure about the first question, but as for the second, you
could do a few different things. You could just pass the tuple itself
into the function and have the tuple unpacked inside the function.

<code>

f(a)

def f (tuple):
x,y,z = tuple

</code>

You could also pass the elements of the tuple in:

f(a[0], a[1], a[2])

That would do it the way you describe in your post.

Mike

Jul 25 '07 #2
On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,

I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.
http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsection
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
>>def foo(a, b, c): print a, b, c
....
>>t = (1, 2, 3)
foo(*t)
1 2 3

Have a look at the official tutorial, 4.7.4 http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg
HTH,
Stargaming
Jul 25 '07 #3
On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].

A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsection
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
>def foo(a, b, c): print a, b, c
...
>t = (1, 2, 3)
foo(*t)

1 2 3

Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg

HTH,
Stargaming
Hi Stargaming,

I know the * operator. However, a 'partial unpack' does not seem to
work.

def g():
return (1,2)

def f(a,b,c):
return a+b+c

f(*g(),10) will return an error.

Do you know how to get that to work?

Thanks,
cg
Jul 25 '07 #4
On Jul 25, 10:46 am, beginner <zyzhu2...@gmail.comwrote:
On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsection
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
>>def foo(a, b, c): print a, b, c
...
>>t = (1, 2, 3)
>>foo(*t)
1 2 3
Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg
HTH,
Stargaming

Hi Stargaming,

I know the * operator. However, a 'partial unpack' does not seem to
work.

def g():
return (1,2)

def f(a,b,c):
return a+b+c

f(*g(),10) will return an error.

Do you know how to get that to work?

Thanks,
cg
As I mentioned, you can access the elements individually using square
brackets. The following works:

f(g()[0], g()[1], 10)

But it's not clear. Unfortunately, I'm not seeing much else for tuple
unpacking except the obvious:

a,b=g()
f(a,b,10)
Mike

Jul 25 '07 #5
On Jul 25, 11:00 am, kyoso...@gmail.com wrote:
On Jul 25, 10:46 am, beginner <zyzhu2...@gmail.comwrote:


On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsection
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
>def foo(a, b, c): print a, b, c
...
>t = (1, 2, 3)
>foo(*t)
1 2 3
Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg
HTH,
Stargaming
Hi Stargaming,
I know the * operator. However, a 'partial unpack' does not seem to
work.
def g():
return (1,2)
def f(a,b,c):
return a+b+c
f(*g(),10) will return an error.
Do you know how to get that to work?
Thanks,
cg

As I mentioned, you can access the elements individually using square
brackets. The following works:

f(g()[0], g()[1], 10)

But it's not clear. Unfortunately, I'm not seeing much else for tuple
unpacking except the obvious:

a,b=g()
f(a,b,10)

Mike- Hide quoted text -

- Show quoted text -
Unfortunately f(g()[0], g()[1], 10) is calling g() twice. Sometimes
this is not a good idea.
a,b=g()
f(a,b,10)
would work until you want it to be an expression.

Jul 25 '07 #6
beginner wrote:
On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
>On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].

A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few
implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsectio n
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
def foo(a, b, c): print a, b, c
...
>>t = (1, 2, 3)
foo(*t)

1 2 3

Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg

HTH,
Stargaming

Hi Stargaming,

I know the * operator. However, a 'partial unpack' does not seem to
work.

def g():
return (1,2)

def f(a,b,c):
return a+b+c

f(*g(),10) will return an error.

Do you know how to get that to work?
f(*(g() + (10,))

Not the most beautiful solution, but it works.

Diez
Jul 25 '07 #7
beginner <zy*******@gmail.comwrites:
I know the * operator. However, a 'partial unpack' does not seem to work.
A few other posters have mentioned ways around this, but you might ask
yourself what coding situation makes you want to do this stuff in the
first place. I won't say there's never a reason for it, but a lot of
times, a list containing a mixture of scalars and lists/tuples is a
sign that your underlying data representation is contorted. Things
are logically single values or they are logically lists of values, and
that mixed representation is often a sign that the item logically
should be a list, and you're hairing up the program with special
treatment of the case where the list has exactly one element.

I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want
[[1,2,], [3,], [5,6]] without the special treatment and flattening.
Jul 25 '07 #8
beginner wrote:
On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
>On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
>>Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsectio n
>>Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
def foo(a, b, c): print a, b, c
...
>>>>t = (1, 2, 3)
foo(*t)
1 2 3

Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
>>Thanks,
cg
HTH,
Stargaming

Hi Stargaming,

I know the * operator. However, a 'partial unpack' does not seem to
work.

def g():
return (1,2)

def f(a,b,c):
return a+b+c

f(*g(),10) will return an error.

Do you know how to get that to work?

Thanks,
cg

Were this not hypothetical, I would make use of the commutative property
of addition:

f(10, *g())

Proof:

1+2+10 = 10+1+2
Also, this has not been suggested:

pydef g():
.... return (1,2)
....
pydef f(a,b,c):
.... return a+b+c
....
pyf(c=10, *g())
13
James
Jul 25 '07 #9
ky******@gmail.com wrote:
On Jul 25, 9:50 am, beginner <zyzhu2...@gmail.comwrote:
>Another question is how do I pass a tuple or list of all the
aurgements of a function to the function. For example, I have all the
arguments of a function in a tuple a=(1,2,3). Then I want to pass each
item in the tuple to a function f so that I make a function call
f(1,2,3). In perl it is a given, but in python, I haven't figured out
a way to do it. (Maybe apply? but it is deprecated?)
I'm not sure about the first question, but as for the second, you
could do a few different things. You could just pass the tuple itself
into the function and have the tuple unpacked inside the function.
OR you could use the syntax invented for just that purpose ;).
>>t = 1, 2, 3
f(*t)
bam! :)

This works with dicts as well (for giving keyword arguments). There you
prepend ** (two asterisk to your dict).
Simple :)
/W
Jul 25 '07 #10
On Jul 25, 8:46 am, beginner <zyzhu2...@gmail.comwrote:
On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsection
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
>>def foo(a, b, c): print a, b, c
...
>>t = (1, 2, 3)
>>foo(*t)
1 2 3
Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg
HTH,
Stargaming

Hi Stargaming,

I know the * operator. However, a 'partial unpack' does not seem to
work.

def g():
return (1,2)

def f(a,b,c):
return a+b+c

f(*g(),10) will return an error.

Do you know how to get that to work?


You can use the "partial" method from functools:

import functools

sum_of_three = functools.partial(f, *g())(10)
--
Hope this helps,
Steven
Jul 25 '07 #11
On Jul 25, 12:00 pm, kyoso...@gmail.com wrote:
On Jul 25, 10:46 am, beginner <zyzhu2...@gmail.comwrote:
On Jul 25, 10:19 am, Stargaming <stargam...@gmail.comwrote:
On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
Hi,
I am wondering how do I 'flatten' a list or a tuple? For example, I'd
like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
A recursive function, always yielding the first element of the list,
could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search?
query=flatten&section=PYTHONCKBK&type=Subsection
Another question is how do I pass a tuple or list of all the aurgements
of a function to the function. For example, I have all the arguments of
a function in a tuple a=(1,2,3). Then I want to pass each item in the
tuple to a function f so that I make a function call f(1,2,3). In perl
it is a given, but in python, I haven't figured out a way to do it.
(Maybe apply? but it is deprecated?)
>def foo(a, b, c): print a, b, c
...
>t = (1, 2, 3)
>foo(*t)
1 2 3
Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
current/tut/node6.html#SECTION006740000000000000000
Thanks,
cg
HTH,
Stargaming
Hi Stargaming,
I know the * operator. However, a 'partial unpack' does not seem to
work.
def g():
return (1,2)
def f(a,b,c):
return a+b+c
f(*g(),10) will return an error.
Do you know how to get that to work?
Thanks,
cg

As I mentioned, you can access the elements individually using square
brackets. The following works:

f(g()[0], g()[1], 10)

But it's not clear. Unfortunately, I'm not seeing much else for tuple
unpacking except the obvious:

a,b=g()
f(a,b,10)

Mike
Or if you'd rather write it in one line:

f(*(g() + (10,)))

George

Jul 25 '07 #12
Here's a quick flatten() function:

def flatten(obj):
if type(obj) not in (list, tuple, str):
raise TypeError("String, list, or tuple expected in
flatten().")
if len(obj) == 1:
if type(obj[0]) in (tuple, list):
return flatten(obj[0])
else:
return [obj[0]]
else:
return [obj[0]] + flatten(obj[1:])

x = [1, 2, (3, 4)]
y = (1, 2, [3, 4])
z = "It even works with strings!"
d = {"foo": "bar", "baz": "bat"}

print flatten(x)
print flatten(y)
print flatten(z)
print flatten(d)

Jul 25 '07 #13
On Jul 25, 10:33 am, Jeff <jeffo...@gmail.comwrote:
def flatten(obj):
if type(obj) not in (list, tuple, str):
raise TypeError("String, list, or tuple expected in
flatten().")
if len(obj) == 1:
if type(obj[0]) in (tuple, list):
return flatten(obj[0])
else:
return [obj[0]]
else:
return [obj[0]] + flatten(obj[1:])
This seems to work fine only if the last object is the only one with
the tuple or list. For example:
>>y = [(1,2),3,4]
y
[(1, 2), 3, 4]
>>print flatten(y)
[(1, 2), 3, 4]

if the last line is changed to

return flatten([obj[0]]) + flatten(obj[1:])

then it will unpack tuples/lists anywhere in the main collection being
flattened:
>>y
[(1, 2), 3, 4]
>>flatten(y)
[1, 2, 3, 4]
>>z = [1,(2,3),4]
flatten(z)
[1, 2, 3, 4]
>>x
[1, 2, (3, 4)]
>>flatten(x)
[1, 2, 3, 4]
>>k = [(1,2),(3,4)]
flatten(k)
[1, 2, 3, 4]

Jul 25 '07 #14
On 2007-07-25, Jeff <je******@gmail.comwrote:
Here's a quick flatten() function:

def flatten(obj):
if type(obj) not in (list, tuple, str):
raise TypeError("String, list, or tuple expected in
flatten().")
if len(obj) == 1:
if type(obj[0]) in (tuple, list):
return flatten(obj[0])
else:
return [obj[0]]
else:
return [obj[0]] + flatten(obj[1:])

x = [1, 2, (3, 4)]
y = (1, 2, [3, 4])
z = "It even works with strings!"
d = {"foo": "bar", "baz": "bat"}
e = [[1], 2, 3, , 4]
f = [1, 2, 3, 4, []]

--
Neil Cerutti
Jul 25 '07 #15
On 2007-07-25, Neil Cerutti <ho*****@yahoo.comwrote:
On 2007-07-25, Jeff <je******@gmail.comwrote:
>Here's a quick flatten() function:

def flatten(obj):
if type(obj) not in (list, tuple, str):
raise TypeError("String, list, or tuple expected in
flatten().")
if len(obj) == 1:
if type(obj[0]) in (tuple, list):
return flatten(obj[0])
else:
return [obj[0]]
else:
return [obj[0]] + flatten(obj[1:])

x = [1, 2, (3, 4)]
y = (1, 2, [3, 4])
z = "It even works with strings!"
d = {"foo": "bar", "baz": "bat"}

e = [[1], 2, 3, , 4]
Please excuse my bad typography. The above should've been

e = [[1], 2, 3, 4].

--
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
Jul 25 '07 #16
def flatten(listOfLists):
return list(chain(*listOfLists))
>From http://www.python.org/doc/2.4/lib/it...s-recipes.html
--
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks: http://del.icio.us/edcrypt
Jul 25 '07 #17
Sorry about that. Hopefully, this should work ;)

def flatten(obj):
if type(obj) not in (list, tuple, str):
raise TypeError("String, list, or tuple expected in
flatten().")
if len(obj) == 1:
if type(obj[0]) in (tuple, list):
return flatten(obj[0])
else:
return [obj[0]]
else:
if type(obj[0]) in (list, tuple):
return flatten(obj[0]) + flatten(obj[1:])
else:
return [obj[0]] + flatten(obj[1:])
x = (1, 2, [3, 4, (5, 6)])
y = ([1, 2, (3, 4)], 5, 6)
z = (1, [2, 3, (4, 5)], 6)

print flatten(x)
print flatten(y)
print flatten(z)

Jul 25 '07 #18
On Jul 25, 3:05 pm, "Eduardo \"EdCrypt\" O. Padoan"
<eopad...@altavix.comwrote:
def flatten(listOfLists):
return list(chain(*listOfLists))
Fromhttp://www.python.org/doc/2.4/lib/itertools-recipes.html

--
EduardoOPadoan (eopadoan->altavix::com)
Bookmarks:http://del.icio.us/edcrypt
That doesn't necessarily work:

import itertools

x = (1, 2, [3, 4, (5, 6)])
y = ([1, 2, (3, 4)], 5, 6)
z = (1, [2, 3, (4, 5)], 6)

def flatten(listOfLists):
return list(itertools.chain(*listOfLists))

print flatten(x)
print flatten(y)
print flatten(z)

==TypeError: chain argument #1 must support iteration

Jul 25 '07 #19
On Jul 25, 11:33 am, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
beginner <zyzhu2...@gmail.comwrites:
I know the * operator. However, a 'partial unpack' does not seem to work.

A few other posters have mentioned ways around this, but you might ask
yourself what coding situation makes you want to do this stuff in the
first place. I won't say there's never a reason for it, but a lot of
times, a list containing a mixture of scalars and lists/tuples is a
sign that your underlying data representation is contorted. Things
are logically single values or they are logically lists of values, and
that mixed representation is often a sign that the item logically
should be a list, and you're hairing up the program with special
treatment of the case where the list has exactly one element.

I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want
[[1,2,], [3,], [5,6]] without the special treatment and flattening.
Very good question. It is well possible that the problem is my
programming style. I am new to python and am still developing a style
that works for me. A lot of things that work in perl does not seem to
work. Unpacking and flattening are just two examples.

I need nested lists to represent nested records in a script. Since the
structure of the underlying data is nested, I think it is probably
reasonable to represent them as nested lists. For example, if I have
the below structure:

Big Record
Small Record Type A
Many Small Record Type B
Small Record Type C

It is pretty natural to use lists, although after a while it is
difficult to figure out the meaning of the fields in the lists. If
only there were a way to 'attach' names to members of the list.

For the unpacking question, I encountered it when working with list
comprehensions. For example:

[ f(*x,1,2) for x in list] is difficult to do if I don't want to
expand *x to x[0]..x[n]. There are usually 7-10 items in the list and
it is very tedious and error prone.

The second problem is from a nested list comprehension. I just needed
something to flatten the list at the moment.

I am still forming my way to do things in python via trial and error.
It is well possible that this is not the natural way to do things.
Jul 26 '07 #20
Also, this has not been suggested:
>
pydef g():
... return (1,2)
...
pydef f(a,b,c):
... return a+b+c
...
pyf(c=10, *g())
13

James- Hide quoted text -

- Show quoted text -
Great idea.

Jul 26 '07 #21
Not the most beautiful solution, but it works.

Diez- Hide quoted text -

- Show quoted text -
Yeah it works! Thanks.

Jul 26 '07 #22
On Wed, 25 Jul 2007 15:46:58 +0000, beginner wrote:
I know the * operator. However, a 'partial unpack' does not seem to
work.

def g():
return (1,2)

def f(a,b,c):
return a+b+c

f(*g(),10) will return an error.

No it doesn't, it _raises_ an exception. This is a function that returns
an error:

def function():
"""Returns an error."""
return Error() # defined elsewhere

But to answer your question:
Do you know how to get that to work?
It's a little bit messy, but this works:
>>f(*(g() + (10,)))
13

This is probably easier to read:
>>t = g() + (10,); f(*t)
13
--
Steven.

Jul 26 '07 #23
On Wed, 25 Jul 2007 09:33:26 -0700, Paul Rubin wrote:
Things
are logically single values or they are logically lists of values
Except for strings, and string-like objects.

And files.

And records/structs, and tuples.

And lists. And sets.

And bit strings. And tree-like structures.

And, well, just about everything really.

But apart from those minor exceptions, I agree completely with your
recommendation.

(Ha ha only serious.)
--
Steven.

Jul 26 '07 #24
For example, if I have
the below structure:

Big Record
Small Record Type A
Many Small Record Type B
Small Record Type C

It is pretty natural to use lists, although after a while it is
difficult to figure out the meaning of the fields in the lists. If
only there were a way to 'attach' names to members of the list.
You could use dictionaries:

big_record = {
"small_record_a": { ... },
"many_small_record_b": {
"sub_record_of_b": { ... },
"sub_record_of_b2": { ... },
},
"small_record_c": { ... },
}

Jul 26 '07 #25
On Thu, 26 Jul 2007 00:58:10 +0000, beginner wrote:
I need nested lists to represent nested records in a script. Since the
structure of the underlying data is nested, I think it is probably
reasonable to represent them as nested lists. For example, if I have
the below structure:

Big Record
Small Record Type A
Many Small Record Type B
Small Record Type C

It is pretty natural to use lists, although after a while it is
difficult to figure out the meaning of the fields in the lists. If
only there were a way to 'attach' names to members of the list.
That's where you may start looking into classes. The simplest one is for
just holding attributes seems to be the "bunch":

In [15]: class Bunch(object):
....: def __init__(self, **kwargs):
....: self.__dict__ = kwargs
....:

In [16]: small_a = Bunch(foo=42, bar=23)

In [17]: many_b = [1, 2, 3]

In [18]: small_c = Bunch(name='eric', profession='viking')

In [19]: big_record = Bunch(small_a=small_a, many_b=many_b, small_c=small_c)

In [20]: big_record.small_a.bar
Out[20]: 23

In [21]: big_record.many_b[1]
Out[21]: 2

For the unpacking question, I encountered it when working with list
comprehensions. For example:

[ f(*x,1,2) for x in list] is difficult to do if I don't want to
expand *x to x[0]..x[n]. There are usually 7-10 items in the list and
it is very tedious and error prone.
If you are the designer of `f` then just receive the whole `x` as *one*
argument.

Ciao,
Marc 'BlackJack' Rintsch
Jul 26 '07 #26

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

Similar topics

23
by: Francis Avila | last post by:
Below is an implementation a 'flattening' recursive generator (take a nested iterator and remove all its nesting). Is this possibly general and useful enough to be included in itertools? (I know...
1
by: John Hunter | last post by:
I am writing a python extension module and have a reference counting question My function looks like static PyObject * pokereval_seven_cards(PyObject *self, PyObject *args) { int i;
9
by: Yomanium Yoth Taripoät II | last post by:
HI, 1) what are the differences between list and tuple? 2) how to concatenate tuple and list? no method, no opérator? 3) im looking the fucking manual, and cant add value in my tuple, when it...
10
by: bearophile | last post by:
This is my first Python program (it's an improvement of a recursive version by Luther Blissett). Given a list like this: , ]]] It produces the "flatted" version: I think this operation is...
3
by: Bengt Richter | last post by:
What am I missing? (this is from 2.4b1, so probably it has been fixed?) def flatten(list): l = for elt in list: ^^^^--must be expecting list instance or other sequence t = type(elt) if t...
14
by: Richard | last post by:
I have a large list of two element tuples. I want two separate lists: One list with the first element of every tuple, and the second list with the second element of every tuple. Each tuple...
32
by: Robin Becker | last post by:
Is there some smart/fast way to flatten a level one list using the latest iterator/generator idioms. The problem arises in coneverting lists of (x,y) coordinates into a single list of...
10
by: rshepard | last post by:
While working with lists of tuples is probably very common, none of my five Python books or a Google search tell me how to refer to specific items in each tuple. I find references to sorting a list...
7
by: Shafik | last post by:
Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
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,...
0
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...

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.