[Tutor] populating an array or using a dictionary
Kent Johnson
kent37 at tds.net
Sun Oct 21 22:13:02 CEST 2007
Michael Langford wrote:
> A neater way to do it looks like:
>
> dic2 = {}
> countOfVars=40
> for line in file('foo.dat'):
> tokens = line.split()
> dval = tokens[0]
> ls = []
> for i in range(1,countOfVars+1):
> ls.append(float(tokens[i]))
> dic2[dval]=tuple(ls)
> print dic2
This is not very idiomatic. You can iterate tokens like this:
ls = []
for token in tokens:
ls.append(float(token))
This can easily be replaced with a list comprehension:
ls = [ float(token) for token in tokens ]
or it can be written using map() (one of the few situations where I
prefer map() to a list comp):
ls = map(float, tokens)
Kent
Kent
More information about the Tutor
mailing list