473,383 Members | 1,717 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,383 software developers and data experts.

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 1424
def descend(iterable):
if hasattr(iterable, '__iter__'):
for element in iterable:
descend(element)
else:
do_something(iterable)

This will just do_something(object) 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*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.


A non-recursive approach:

def enumerate_ex(items):
stack = [(enumerate(items), items)]
while stack:
en, seq = stack[-1]
for index, item in en:
if isinstance(item, list):
stack.append((enumerate(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(data):
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.com> wrote in message
news:11********************@g44g2000cwa.googlegrou ps.com...
This will just do_something(object) 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(items):
stack = [(enumerate(items), items)]
while stack:
en, seq = stack[-1]
for index, item in en:
if isinstance(item, list):
stack.append((enumerate(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
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...
6
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...
1
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...
11
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....
105
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...
8
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
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...
6
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...
15
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
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
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...

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.