简体   繁体   中英

2D lists generation Python

I know that to generate a list in Python you can use something like:

l = [i**2 for i in range(5)]

instead of using for loop like:

l = []
for i in range(5):
    l.append(i**5)

Is there a way to do 2D lists without using for loops like this:

map = [[]]

for x in range(10):
    row = []
    for y in range(10):
        row.append((x+y)**2)
    map.append(row)

Is there any other alternatives to represent 2D arrays in Python ?

Use a list comprehension here too:

>>> [ [(x+y)**2 for y in range(10)] for x in range(10)]
[[0, 1, 4, 9, 16, 25, 36, 49, 64, 81], [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], [4, 9, 16, 25, 36, 49, 64, 81, 100, 121], [9, 16, 25, 36, 49, 64, 81, 100, 121, 144], [16, 25, 36, 49, 64, 81, 100, 121, 144, 169], [25, 36, 49, 64, 81, 100, 121, 144, 169, 196], [36, 49, 64, 81, 100, 121, 144, 169, 196, 225], [49, 64, 81, 100, 121, 144, 169, 196, 225, 256], [64, 81, 100, 121, 144, 169, 196, 225, 256, 289], [81, 100, 121, 144, 169, 196, 225, 256, 289, 324]]

The more efficient way to do that is using numpy.meshgrid(). Here you have an example:

i = np.arange(1,10)
I,J = np.meshgrid(i,i)
array = (I+J)**2

and array has the desired form.

You could compare the performance between your method and meshgrid. Meshgrid is C-implemented, so it's very fast!

If you need a list from an array, you could use the array.tolist() method.

You might also consider implementing nd arrays using numpy , a scientific computing package for Python. Numpy array objects confer a few advantages over nested lists:

  • nd array slicing, for example (taken from numpy documentation ):

     x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) #creates the array x[:,1] # returns the first column 
  • easy manipulation of nd arrays with methods such as transpose, reshape and resize.

  • easy implementation of mathematical operations on arrays.

Of course this may be more machinery than you actually need, so it could be the case that nested list comprehension is sufficient for your purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM