![]() |
How would you write this in Python?
:
for (a = i = 0; i < 3; ++i)Further, would you consider converting the lists of lists into single lists? Also, would you move invariants (such as 2*math.pi or myImage.GetWidth ()) outside the comprehension to avoid the overhead? |
I believe this would be the equivalent in Python:
:
a = 0 |
It might be more Pythonic to use a generator and sum:
:
a = sum(grid[i][j] * map[i][j] for j in range(3) for i in range(3))However, I haven't yet devised a better solution. I'll think about it, and see if I can't come up with something more elegant. |
Frankly, what Python really needs is a n-dimensional rectangular grid object. Something like:
:
grid = Array(3, 3) # 3 by 3 array |
I thought about using a generator to flatten them to one dimension, then operate on those. I appreciate your looking at it. I still am, too. You got the thrust of my question; I knew how to just translate it.
|
I believe the numpy module supports multidimensional arrays.
|
Quote:
Speaking of flattening lists: :
def flatten(seq):Armed with the above function, this should work. :
a = sum(x * y for x in flatten(grid) for y in flatten(map)) |
Arevos, I'm not 100% sure about this but I believe your logic is flawed. You are multiplying each value in the first list by each value in second list and adding the results, while the original code multiplies each value in the first list only by the single corresponding value in the second list and adds the results.
I wrote a function, align, that allows you to achieve this functionality: :
def align(a, b, func)::
a = sum(align(grid, map, lambda x, y: x * y)) |
Quote:
The original code I had went: :
a = sum(x * y for x, y in zip(flatten(grid), flatten(map))) |
Oh, wow! I didn't know you could iterate over multiple variables in a list comprehension! Well, that makes my code almost useless. :p
I originally wrote a flatten function as well, but since I couldn't figure out how to do just that, I wrote a new function, align. By the way, what does the zip function do? |
| All times are GMT -5. The time now is 12:18 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC