473,569 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NEWB: General purpose list iteration?

I'm a real Python NEWB and am intrigued by some of Python's features, so I'm
starting to write code to do some things to see how it works. So far I
really like the lists and dictionaries since I learned to love content
addressability in MATLAB. I was wondering it there's a simple routine (I
think I can write a recurisve routine to do this.) to scan all the elements
of a list, descending to lowest level and change something. What I'd like to
do today is to convert everything from string to float. So, if I had a list
of lists that looked like:
[['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1', '4.2']]]]
and I'd like it to be:
[[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3,2], [4.1, 4.2]]]]
is there just a library routine I can call to do this? Right now, I'm using
'for' loops nested to the maximum depth anticipated.

for i in range(len(list) ):
for j in range(len(list[i])):
for k in range(len(list[i][j])):
etc
list[i][j][...] = float(list[i][j][....])

Which works but is not pretty. I was just looking for a way to say:
listb = float(lista)
However, the way I've started jamming everything into lists and
dictionaries, I'm sure I'll be needing to do other in-place conversions
similar to this in the future.

--
Donald Newcomb
DRNewcomb (at) attglobal (dot) net
Aug 12 '05 #1
4 1431
def descend(iterabl e):
if hasattr(iterabl e, '__iter__'):
for element in iterable:
descend(element )
else:
do_something(it erable)

This will just do_something(ob ject) to anything that is not an
iterable. Only use it if all of your nested structures are of the same
depth.

If you used it on the following list of lists

[[something],[[something_else],[other_thing]]]

it would modify something, something_else, and other_thing.

Aug 12 '05 #2
Donald Newcomb wrote:
I*was*wondering *it*there's*a*s imple*routine*( I
think I can write a recurisve routine to do this.) to scan all the
elements of a list, descending to lowest level and change something. What
I'd like to do today is to convert everything from string to float. So, if
I had a list of lists that looked like:
[['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1',
[['4.2']]]]
and I'd like it to be:
[[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3,2], [4.1, 4.2]]]]
is there just a library routine I can call to do this? Right now, I'm
using 'for' loops nested to the maximum depth anticipated.


A non-recursive approach:

def enumerate_ex(it ems):
stack = [(enumerate(item s), items)]
while stack:
en, seq = stack[-1]
for index, item in en:
if isinstance(item , list):
stack.append((e numerate(item), item))
break
yield index, seq[index], seq
else:
stack.pop()
data = [['1.1', '1.2', '1.3'], [['2.1', '2.2'], [['3.1', '3.2'], ['4.1',
'4.2']]]]

for index, value, items in enumerate_ex(da ta):
items[index] = float(value)

# Now let's test the algorithm and our luck with float comparisons
assert data == [[1.1, 1.2, 1.3], [[2.1, 2.2], [[3.1, 3.2], [4.1, 4.2]]]]

Peter

Aug 12 '05 #3

"Devan L" <de****@gmail.c om> wrote in message
news:11******** ************@g4 4g2000cwa.googl egroups.com...
This will just do_something(ob ject) to anything that is not an
iterable. Only use it if all of your nested structures are of the same
depth.


Cool! I'll try it.

--
Donald Newcomb
DRNewcomb (at) attglobal (dot) net
Aug 12 '05 #4

"Peter Otten" <__*******@web. de> wrote in message
news:dd******** *****@news.t-online.com...
A non-recursive approach:

def enumerate_ex(it ems):
stack = [(enumerate(item s), items)]
while stack:
en, seq = stack[-1]
for index, item in en:
if isinstance(item , list):
stack.append((e numerate(item), item))
break
yield index, seq[index], seq
else:
stack.pop()


It's going to take me a while to figure out exactly what that does but it
sure does what I wanted it to.
Thanks.

--
Donald Newcomb
DRNewcomb (at) attglobal (dot) net
Aug 12 '05 #5

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

Similar topics

5
2024
by: Alexandre | last post by:
Hi, Im a newb to dev and python... my first sefl assigned mission was to read a pickled file containing a list with DB like data and convert this to MySQL... So i wrote my first module which reads this pickled file and writes an XML file with list of tables and fields (... next step will the module who creates the tables according to...
6
2126
by: Maarten van Reeuwijk | last post by:
Hi group, I need to parse various text files in python. I was wondering if there was a general purpose tokenizer available. I know about split(), but this (otherwise very handy method does not allow me to specify a list of splitting characters, only one at the time and it removes my splitting operators (OK for spaces and \n's but not for =,...
1
1272
by: Chris | last post by:
I'm developing a thing that gathers data as follows: 1. For all files of a certain name: I. for all lines in each of those files: i. split the /-separated values in each of those lines, and stuff them into a list (or dict or whatever) .... and this is for a hundred or so such files of that name, with each file having a hundred or so of...
11
1974
by: The_Kingpin | last post by:
Hi all, I'm new to C programming and looking for some help. I have a homework project to do and could use every tips, advises, code sample and references I can get. Here's what I need to do. I have a file named books.txt that contains all the informations on the books. Each book is a struc containing 6 fields written on separated line...
105
5272
by: Christoph Zwerschke | last post by:
Sometimes I find myself stumbling over Python issues which have to do with what I perceive as a lack of orthogonality. For instance, I just wanted to use the index() method on a tuple which does not work. It only works on lists and strings, for no obvious reason. Why not on all sequence types? Or, another example, the index() method has...
8
1177
by: manstey | last post by:
Hi, I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i in data: data = data.replace(i,i)
29
2621
by: jaysherby | last post by:
I'm new at Python and I need a little advice. Part of the script I'm trying to write needs to be aware of all the files of a certain extension in the script's path and all sub-directories. Can someone set me on the right path to what modules and calls to use to do that? You'd think that it would be a fairly simple proposition, but I can't...
6
1788
by: John Machin | last post by:
Hi, In general, I'm mainly interested in a template engine for dynamic web pages but would like a general purpose one to avoid learning yet another package for generating e-mail messages, form letters, source code, whatever. In particular, does anyone have much experience with the Python interface to Terence Parr's StringTemplate...
15
3083
by: Macca | last post by:
Hi, My app needs to potentially store a large number of custom objects and be able to iterate through them quickly. I was wondering which data structure would be the most efficient to do this,a hashtable or a generic list. Is using enumerators to iterate through the data structure a good idea? I'd appreciate any suggesstions or advice,
0
7703
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, 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...
0
7930
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. ...
1
7681
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...
0
6290
agi2029
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...
0
5228
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...
0
3662
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...
0
3651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1229
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
950
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...

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.