Vortex.ihrc.fiu.edu



Python listArray is one of the most fundamental data structures in any computational language. Python doesn't have a native array data structure, but it has a data structure called list, which is much more general and can be used as a multidimensional array. For scientific calculation, however, Python list is not very convenient. Python has a math library called numpy, which is much more powerful and easier to use. I’ll introduce numpy later. In this class, I am focusing on the numeric array provided by Python itself, i.e., python list. It is worthwhile knowing the basics of p\ython and how to handle data array without numpy library. List basics1. To define a list you simply write a comma separated list of items in square brackets:myList=[1,2,3,4,5,6]2. A list in Python is just an ordered collection of items which can be of any type. For example,Myaddress=[3225,'West','Foster','Avenue','Chicago','IL',60625]So, in principle a list is more flexible than an array but it is this flexibility that makes things slightly harder when you want to work with a regular structure.3. A list looks like an array because you can use "slicing" notation to pick out an individual element. The index of a list starts from 0. Examining,>>>myList[0]1>>>myList[2]3>>>myList[5]6>>>myList[6]Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> myList[6]IndexError: list index out of range4. Replacing elements in a list. You can directly assign a new value to any elements in a list, for example,>>> myList[2]=100>>> myList[1, 2, 100, 4, 5, 6]You can even assign a different data type to an element, for example,>>> myList[2]='hello'>>> myList[1, 2, 'hello', 4, 5, 6]5. You can define a sublist easily using slicing notation, for example,>>> sublist=myList[2:5]>>> sublist[3, 4, 5]Also try,>>> myList[4:]This is equivalent to>>> myList[4:6][5, 6]>>> myList[:4] [1, 2, 3, 4]This is equivalent to>>> myList[0:4][1, 2, 3, 4]>>> myList[0:6:2][1, 3, 5]6. The list you assign to a slice doesn't have to be the same size as the slice - it simply replaces it even if it is a different size, for example,>>> myList[1, 2, 3, 4, 5, 6]>>> myList=['hello','look']>>> myList['hello', 'look']7. Check length of a list>>>len(myList)68. Basic list operationsLet’s find the maximum value in the list myList (forgetting for a moment that there is a built-in max function)?using the Python code: eg1_list.py.This piece of Python code uses the ‘for…in’ construct to scan through each item in the list. This is a very useful way to access the elements of an array but it isn't the one that most programmers are familiar with. In most cases, arrays are accessed by index and you can do this in Python as well, please see Python code: eg2_list.py.One has to admit the simplicity of the non-index version of the ‘for’ loop, but in many cases the index of the entry is needed. For example, for the previous example if you wanted to return not only the maximum element but also its index position in the list, then, you could use the following code: eg3_list.py.Note that Python has a built-in index method that could return the index position, for example, the code: eg4_list.py.However, there is a potential problem for this non-index version of Python code, please see the following code: eg5_list.py. You get an error message: NameError: name 'mi' is not defined.This problem can be fixed, see code: eg6_list.pyThere is also the slight problem that behind the scene for this method, that is, the computer has to perform the scan of the entire list, which may be a problem for a large array.9. Assigning values to a list. Let’s say we want to initialize a list with zero. There are two easy ways to do it. First, we can use Python comprehension method,>>> myList=[0 for i in range(10)]Second, we can simply use command,>>> myList=[0]*10Also try,>>> myList=[1]*10>>> myList=[1 for i in range(10)]>>> myList=[i for i in range(10)]>>> myList=[i**2 for i in range(10)]>>> myList=[i*2+1 for i in range(10)]>>> myList=[i*0.01 for i in range(10)]10. Two dimensional arrayIn Python, to define a 2D array, all you have to do is to store lists within lists - after all what is a 2D array in Python is just a 1D array of rows. For example,>>> myArray=[[1,2],[3,4],[5,6]]>>> myArray[[1, 2], [3, 4],[5,6]]Then,>>> myArray[0][1, 2]i.e., myArray[0] is just the list [1, 2].>>> myArray[0][1]2So, As long as you build your arrays as nested lists in the way described, then, you can use slicing in the same way as what we just did, that is:myArray[i][j]is the i,jth element of the array. For example,>>> for i in range(len(myArray)):for j in range(len(myArray[i])):print(myArray[i][j])123456Note here, len(myArray) returns the number of rows and len(myArray[i])) returns the number of elements in a row. Notice that there is no need for all of the rows to have the same number of elements, but if you are using a list as an array this is an assumption you need to enforce.Also, you can use the index method to recover the index of an element, but you have to be careful how you do it. For example, to print the row and column index of the element:>>> for row in myArray:for e in row:print(myArray.index(row),row.index(e))0 00 11 01 12 02 111. Initializing a 2D list>>> myArray=[[0 for j in range(4)] for i in range(3)]>>> myArray[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]As you can see here, the inner comprehension,[0 for j in range(4)], creates a row, and then, the outer comprehension creates a list of rows.As before, you can use the index variables in the expression, for example:>>> myArray=[[i*j for j in range(4)] for i in range(3)]>>> myArray[[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]]In general, if you want to work with an ‘m by n’ array use:>>>myArray=[[0 for j in range(n)] for i in range(m)]and everything should work as you would expect.In Python, it is generally easy to get hold of the rows of a matrix:>>>for row in myArray:do something with row12. 3D list>>> myArray=[[[1,2,4,5],[3,4,6,7],[5,6,8,9]],[[1,2,4,5],[3,4,6,7],[5,6,8,9]]]>>> myArray[[[1, 2, 4, 5], [3, 4, 6, 7], [5, 6, 8, 9]], [[1, 2, 4, 5], [3, 4, 6, 7], [5, 6, 8, 9]]]>>> len(myArray) # number of pages 2>>> len(myArray[0]) # number of rows3>>> len(myArray[0][1]) #number of columns4If it’s a 4D list, you may say, books, pages, rows, and columns…13. 1D list calculationLet’s say we have two lists, a=[1, 2, 3, 4] and b=[2, 3, 4, 5], we want to do,[1, 2, 3, 4]+ [2, 3, 4, 5]=[3, 5, 7, 9] and [1, 2, 3, 4]-[2, 3, 4, 5]=[-1, -1, -1, -1]Can we just do,>>>a+b?>>>a-b?It won’t work! There are several ways we can do the job by using Python comprehension.(i)>>>c=[0]*len(a)>>>for i in range(len(a)):c[i]=a[i]+b[i](ii)>>>c=[0]*len(a)>>> c=[a[i]+b[i] for i in range(len(a))]>>> c[3, 5, 7, 9](iii) Using zip() function,>>> c=[a+b for a,b in zip(a,b)]>>> c[3, 5, 7, 9]>>> list(zip(a,b))[(1, 2), (2, 3), (3, 4), (4, 5)](iv) Using map() and lambda function,>>> c=list(map(lambda a,b:a+b,a,b))>>> c[3, 5, 7, 9](v) Using Python list append method>>> c=[] #Create empty list>>> for i in range(0, len(a)):c.append(a[i]+b[i])>>> c[3, 5, 7, 9]list.append(x): Add an item to the end of the list.(vi) Using enumerate() function,>>> c=[var+b[i] for i, var in enumerate(a)]>>> c[3, 5, 7, 9]Exercising a-b, a*b, a/b>>> c=[a[i]-b[i] for i in range(len(a))]>>> c=[a-b for a,b in zip(a,b)]>>> c=list(map(lambda a,b:a-b,a,b))>>> c=[]>>> for i in range(0, len(a)): c.append(a[i]-b[i])>>> c=[var-b[i] for i, var in enumerate(a)]Exercise: 1. a=[10, 17, 7, 23, 8, 3], how do you calculate a*3?>>> c=[a[i]*3 for i in range(len(a))]>>> c=[var*3 for i, var in enumerate(a)]>>> c=[]>>> for i in range(0, len(a)):c.append(a[i]*3)2. Saturated water vapor pressure is solely determined by temperature, , where . On a sunny day, the temperature measurements starting from 0 UTC at 1 h interval are: 5.3, 4.2, 3.8, 3.2, 2.7, 2.2, 2.4, 3.4, 4.0, 5.5, 6.7, 8.0, 9.5, 10.3, 11.9, 12.8, 13.3, 13.5, 12.8, 11.1, 8.3, 7.5, 6.4, 5.8 0C. Please calculate the corresponding saturated water vapor pressure. .Please see: eg7_list.py14. 2D list calculationFor 1D array, it seems that Python can reasonably handle the array calculation using the Python list comprehension. Then, what about 2D array or multiple dimensional array? Do all these commands still work? Lets’ try 2D lists: X=[[12,7,3,4],[4 ,5,6,5],[7 ,8,9,6]], Y=[[5,8,1,3],[6,7,3,8],[4,5,9,7]].>>> X=[[12,7,3,4],[4 ,5,6,5],[7 ,8,9,6]]>>> Y=[[5,8,1,3],[6,7,3,8],[4,5,9,7]]2D list calculationCan we do,>>> Z=[X*Y for X,Y in zip(X,Y)]Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> Z=[X*Y for X,Y in zip(X,Y)] File "<pyshell#57>", line 1, in <listcomp> Z=[X*Y for X,Y in zip(X,Y)]TypeError: can't multiply sequence by non-int of type 'list'It does not work!!We have to use for loop to do the job.>>> Z=[[0 for i in range(len(X[i]))] for i in range(len(X))]>>> for i in range(len(X)):for j in range(len(X[i])):Z[i][j]=X[i][j]*Y[i][j]See example: eg8_list.pyThis does not look convenient at all. In Python, array calculation can be done using numpy. Before introducing numpy, let’s review array calculation.1. Array Element-by-Element Calculation Say, we have two 2D arrays:a = 1 2 3 4 5 6 7 8 9b = 3 2 1 6 5 4 9 8 7Then, the array element-by-element calculation will beab= 1*3 2*2 3*1 3 4 3 4*6 5*5 6*4 = 24 25 24 7*9 8*8 9*7 63 64 63This is just the same as what we did previously for 1D arrays: a=[1, 2, 3, 4], b=[2, 3, 4, 5], and ab=[2, 6, 12, 20].2. Matrix multiplicationMatrix calculation rules, B=[B1 B2 ... Bn]; A(m, 1) B(1, n); (m, n)BA=A1B1+A2B2+...+AnBnThis is the so-called array dot product.ExamplesA = 1 2 3 4 5 6 7 8 9Element-by-element multiplication of AA will be 1*1 2*2 3*3 1 4 9AA = 4*4 5*5 6*6 = 16 25 36 7*7 8*8 9*9 49 64 81Matrix multiplication of AA will be 1*1+2*4+3*7 1*2+2*5+3*8 1*3+2*6+3*9 30 36 42AA = 4*1+5*4+6*7 4*2+5*5+6*8 4*3+5*6+6*9 = 66 81 96 7*1+8*4+9*7 7*2+8*5+9*8 7*3+8*6+9*9 102 126 150How to do matrix multiplication using list?>>> X=[[1,2,3],[4,5,6],[7,8,9]]>>> Y=[[3,2,1],[6,5,4],[9,8,7]]See example eg9_list.py ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download