August 16th, 2003, 12:04 AM
Bidimensional arrays in Python
Hi, my problem is simple : I'm trying to make some 2x2 matrix operations, similar to the C code like(not necessarily int). And honestly, I have no clue about how to do that in Python. So how can I do that ?
I COULD make a "flat", one-dimensional array, and take each x'th element, but I'd be surprised if nobody ever worked with Python and matrices.
Time is the greatest of teachers ; sadly, it kills all of its students.
- Hector Berlioz
August 16th, 2003, 02:40 AM
I'm not trained in Python but isn't :
what you're looking for ? Just an array of arrays
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
[1, 2, 3]
August 16th, 2003, 08:37 AM
Also, note that what you will be creating is not an array, but a list. A mutable list. You can't directly create an empty array, but you can of course create an array filled with default values:
[[0 for i in range(2)] for i in range(2)]
For more info, see Python Tutorial: List Comprehensions
Last edited by percivall; August 16th, 2003 at 08:40 AM.
August 16th, 2003, 11:04 AM
Ah, that'll teach me to RTFM. Thanks.
August 18th, 2003, 08:42 AM
Another way of doing the same thing:
This is essentially the same as the list comprehension in the earlier post, but a little less typing.
August 19th, 2003, 09:48 AM
August 19th, 2003, 10:18 AM
List comprehension is most powerful when combined with a function, such as:
This is of course also possible with a regular list comprehension...
[(lambda i: [i, chr(i)])(i) for i in range(65, 123)]
Okay, not very useful. Anyway, it lets you do stuff in a nice way.
[[i, chr(i)] for i in range(65, 123)]
Last edited by percivall; August 19th, 2003 at 10:29 AM.
August 19th, 2003, 05:03 PM
I'd be enclined to use the second . Smaller and and nicer to look at, plus since it does less (doesnt create a lambda) it should be slightly more efficent (in theory). Does give some idea of whats possible. Good for setting up lists .
good to know thanks,
September 4th, 2003, 09:08 PM