Hi all,
I'm new to Python. I'm trying to create a fast function to do the following:
t = [['a1','a2'],['b1'],['c1'],['d1']]
l = [1,2,3,4,5] create_nested_list(t,l)
[[1, 2], [3], [4], [5]]
t is some sort of template. This is what I have now:
def create_nested_list(template,l_orig):
'''Uses a template to create a new list
t = [['a1','a2'],['b1'],['c1'],['d1']]
l = [1,2,3,4,5] create_nested_list(t,l)
[[1, 2], [3], [4], [5]]
'''
tl = map(len, template)
# Input size check
if reduce(lambda x,y: x+y, tl) != len(l_orig):
raise "Wrong input size"
l = l_orig
new_nested_list = []
for x in tl:
q = []
i = 0
while i < x:
q.append(l.pop(0))
i += 1
new_nested_list.append(q)
return new_nested_list
I'd like to know if it is possible to make this faster (using Python magic I
don't know of yet), because this function will be called a lot
('constantly').
Thanks in advance,
Stan. 2 1359
Are there only a few, unchanging templates? If so, (dynamiclly) create
a function for each template. This will be nearly the fastest you can
go in Python, excluding the time to create and byte-compile the nesting
function.
# This code is in the public domain
def make_nesting_expression(l, s):
result = []
for c in l:
if isinstance(c, list):
sub, s = make_nesting_expression(c, s)
result.append(sub)
else:
result.append("l[%d]" % s)
s += 1
print "make_nesting_expression", l, result
return "[" + ",".join(result) + "]", s
def make_nesting_function(l):
return eval("lambda l: %s" % make_nesting_expression(l, 0)[0])
t = [['a1','a2'],['b1'],['c1'],['d1']]
l = [1, 2, 3, 4, 5]
f = make_nesting_function(t)
print f(l)
Jeff
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
iD8DBQFCeNpeJd01MZaTXX0RAn4vAJ4+7ZFhwCYh+QSSqeUoNp h/frm32QCggwkt
hOuLLmswcC3Fz4g47NdlJVk=
=ZyPe
-----END PGP SIGNATURE-----
Jeff Epler wrote: Are there only a few, unchanging templates? If so, (dynamiclly)
create a function for each template. This will be nearly the fastest you
can go in Python, excluding the time to create and byte-compile the
nesting function.
# This code is in the public domain def make_nesting_expression(l, s): result = [] for c in l: if isinstance(c, list): sub, s = make_nesting_expression(c, s) result.append(sub) else: result.append("l[%d]" % s) s += 1 print "make_nesting_expression", l, result return "[" + ",".join(result) + "]", s
def make_nesting_function(l): return eval("lambda l: %s" % make_nesting_expression(l, 0)[0])
t = [['a1','a2'],['b1'],['c1'],['d1']] l = [1, 2, 3, 4, 5] f = make_nesting_function(t) print f(l)
Jeff
Nice approach! Though I'm wondering, because the "template" is so close
to the function you're trying to create, why not just create the
function directly? As in: f5 = lambda p: (p[0:2], p[2], p[3], p[4]) f5(('a', 'b', 'c', 'd', 'e', 'f'))
(('a', 'b'), 'c', 'd', 'e')
Or if you need to be able to remember what the template looks like
(e.g. reading/writing it as a string in a file), you can always create
the function by evaluating a (properly constructed) template string:
f5 = eval("lambda p: (p[0:2], p[2], p[3], p[4])") f5(('a', 'b', 'c', 'd', 'e', 'f'))
(('a', 'b'), 'c', 'd', 'e')
If you want to avoid lambdas, the same ideas can be used with short
defs, e.g.:
def f5(p): return (p[0:2], p[2], p[3], p[4])
Incidentally, these solutions raise an IndexError if your list is too
short, and silently drop the end of a list that's too long.
That's my keep-it-simple-I-might-understand-it approach.
Jason This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Andy Baker |
last post by:
Hi there,
I'm learning Python at the moment and trying to grok the thinking behind
it's scoping and nesting rules.
I was googling for nested functions and found this Guido quote:...
|
by: Alex Vinokur |
last post by:
=========================================
Windows 2000
CYGWIN_NT-5.0 1.3.22(0.78/3/2)
GNU gcc version 3.2 20020927 (prerelease)
=========================================
Here is some program...
|
by: CoolPint |
last post by:
I read in books that nested class cannot access private members of
nesting class and vice versa unless they are made friends. Somehow, my
compiler is letting my nested class member functions access...
|
by: Eddie Parker |
last post by:
Hi!
I'm having an interesting problem that I can't seem to get to work, and
I'm curious if someone could either a) tell me how to make it work, or
b) tell me why it *can't* work. :)
Anyhow,...
|
by: cyberdave |
last post by:
Someone please help me!
I have a template class like this:
--------------------------------------------------
template<typename T>
class List
{
public:
|
by: sushant |
last post by:
hi all,
suppose i have 2 loops one inside the other, like this
1) for(i=0;i<=100;i++)
{
for(j=0;j<=10;j++)
{
some code;
}
|
by: Robert W. |
last post by:
I've almost completed building a Model-View-Controller but have run into a
snag. When an event is fired on a form control I want to automatically
updated the "connnected" property in the Model. ...
|
by: bigbarn |
last post by:
Hi - I can't seem to figure this one out, help is appreciated:
Header file:
template <class T>
class Foo {
T val;
};
template<class T>
class Bar {
|
by: card |
last post by:
Hi everyone,
I have a question about referencing a nested class contained within a templated class. Of course the best way to show you is by example. Here's my templated classes:
#include...
|
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...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
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...
|
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...
|
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,...
|
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: 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,...
|
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...
|
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...
| |