#!/usr/bin/env python # file: lecture_31/example.py # # demonstrate some basic data structures # # include # import os import sys import numpy as np # create a list, which can be thought of as an array # #print("1D array:") #xl = ["Alex", "Jordan"] #xl.append("Joe") #xl.append("Bob") #print(xl) #xl2 = ["1.11", "2.22", "3.33"] #print(xl2) #xl.append(int(27)) #xl.append(float(27.0)) #print("xl:", xl) #print("xl2:", xl2) #xl.append(xl2) #print("xl appended with xl2:", xl) #xl.append(xl) #print("xl appended with xl:", xl) # do some more lists # #xl3 = [1.11, 2.22, 3.33] #print(xl3) #xl2 = xl3 #xl2.append(float(1.11)) #print("the new xl2: ", xl2) #xl2.append("Wow!") #print("the new and better xl2: ", xl2) # let's go back to basic Python # #zz = [[1.11, 2.22, 3.33], "Joe", [4.44, 5.55]] #print(zz) # # create a 1D numeric array # #print("now try this with numpy:") #x = np.array([1.11, 2.22, 3.33]) #print(x) #print("a true 32-bit float array:") #y = np.array([1.11, 2.22, 3.33], np.float32) #print(y) #z = float(23.23) #print(z) # create a 2D numeric array # #print("2D array:") #z = np.array([[1.11, 2.22, 3.33], [4.44, 5.55, 6.66]], np.float32) #print(z) # create a list # #print("---> list:") #l = ["alex", "jordan"] #print("list: ", l) #l.append("mike") #print("append: ", l) ## #l.append(float(27.27)) #print ("append: ", l) #l.append("daniel") #l.append(float(35.01)) #print ("append: ", l) ## #l = [["joe", float(3.33)], ["mary", float(2.0)]] #print("heterogeneous: ", l) #l.append(float(35.01)) #print("heterogeneous: ", l) #l.append([27.0, 99.0]) #l.append("Alex") #print("heterogeneous: ", l) ## # loop over a list # #print("--> looping:") #l = ["aaa", [1.0, 2.0, 3.0], "bbb", [4.0], "ccc"] #for element in l: # print(element) #print("--> end of looping") # #print("--> indexed looping:") #for i in range(0, len(l)): # print(i, l[i]) #print("--> better looping:") #l = [1, 2, 3.77, 4, 5] #for arg in l: # print("arg = ", arg) # list comprehension # #l = [1, 2, 3, 4, 5] #squares = [x**2 for x in l] #print("--> squares: ", squares) # create a dictionary # a = dict(red=4139, green=4127, blue=4098) print("--> dictionaries:") print("orig:", a) print("specific value", a['red']) a['white'] = ["Joe", "313131"] print("new a:", a) a['red'] = ["Alex", "Jordan"] print("overwrite:", a) a["mary"] = float(27.27) a["joe"] = ["car", "house", float(27.27)] print("new version:", a) #a['dict'] = dict(yellow=27, white=2727) ##print("--> better value of a:") ##print(a) #print("printing dictionary:") print("---->:") for key in a: print(" ->", key, a[key]) #print("another dictionary print:") for v, w in enumerate(a): print(">>> index:", v, "key:", w, "[", a[w], "]") # ordered dictionaries are now the default # a = dict(red=4139, green=4127, blue=4098) print(a) # sort a dictionary # print("---->:") for key in a: print(key, a[key]) print("----sorted>:") b = sorted(a) print(b) for key in sorted(a): print(key, a[key])