Thursday, March 16, 2006

Re: st: looping over parallel lists - is there a alternative to "for"?

On Mar 16, 2006, at 8:14 AM, Svend Juul wrote: > But wouldn't it be nice if -foreach- could: > > foreach A of varlist c1-c10 \ B of numlist 4/2 7/1 { > do something with `A' and `B' > }

This is one (of many) areas where Python is simply beautiful. Consider:

mylist = [[1, "a", "I"], [2, "b", "III"], [3, "c", "III"]] for numeral, letter, roman in mylist: print numeral, letter, roman

which produces the following output:

1 a I 2 b II 3 c III

The key things to notice here are that mylist is a list of lists (lists can be nested in Python), and that the for command may be used with multiple items. As we all know, -foreach- cannot be used with multiple items. Nested (macro) lists, however, are possible in Stata by using compound quotes. For example:

loc mylist `" "1 a I" "2 b III" "3 c III" "' foreach element of loc mylist { di "`: word 1 of `element'' `:word 2 of `element'' `:word 3 of `element''" }

will produce exactly the same output as the Python code above.

Note that although Python's for command does permit the use of multiple items, it does not permit the use of multiple lists, something that was possible with Stata's old -for- command. For example, you can't do this:

numerals = [1, 2, 3] letters = ["a", "b", "c"] for n, l in numerals, letters: print n, l

nor this:

for n in numerals, l in letters: print n, l

In practice, this isn't a problem, since there is a simple utility to transform multiple lists (like the lists "numerals" and "letters" above) into a single, nested list (like mylist). Such a utility (to transform macro lists) could easily be written in Stata and, if it were written in Mata, would be very fast even for large lists. Thus, IMHO, the only problem with the Stata example above is that -foreach- cannot be used with multiple items, which is why we have to use the somewhat awkward construction involving inline expansion of the extended macro function "word # of" in the call to -display-. I have no idea how difficult it would be to extend -foreach- in this way, nor have I thought seriously about the issues involved. As I have just shown, however, such an extension might well eliminate any lingering temptations to continue using the now deprecated -for- command.

-- Phil

* * For searches and help try: * http://www.stata.com/support/faqs/res/findit.html * http://www.stata.com/support/statalist/faq * http://www.ats.ucla.edu/stat/stata/


Tag:


Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?