#!/usr/bin/env python # coding: utf-8 # # Data Structures, Functions, and Files # tuples, lists, dicts, and sets # ### Tuple # * A tuple is a 1-d fixed-lenght, immutable sequence of Python objects # * use `()` brackets or 'tuple' # In[1]: tup = ((1, 2, 3, 4, 5, 6), (7, 8, 9)) tup # In[3]: my_list = [2, 4, 6] type(my_list) # In[4]: tup2 = tuple(my_list) tup2 # In[5]: my_string = "Hello, world!" type(my_string) # In[6]: tup3 = tuple(my_string) tup3 # In[7]: tup3[0:5] # In[9]: # tuples are immutable tup3[0] = "h" # In[10]: tup4 = tuple(["foo", (2, 4, 6), range(5)]) tup4 # In[19]: tup4[1].append(3) tup4 # In[18]: tup4.count("foo") # In[28]: seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] seq # In[35]: for a, b, c in seq: print("a = {0}, b = {1}, c = {2}".format(a, b, c)) # In[37]: values = ((a, b, c), (range(20))) values # In[38]: y, *rest = values # In[39]: y # In[40]: rest # ## List # * Defined using `[]` brackets # In[66]: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] type(my_list) # In[67]: my_list # In[68]: new_list = [10, 11, 12, 14, 15] my_list.append(new_list) my_list # In[69]: my_list + new_list # In[70]: my_list.pop(9) my_list # In[71]: my_list.remove(8) my_list # In[72]: new_list + my_list # In[83]: a = [7, 2, 5, 1, 3] a.sort() a # In[77]: type(sort_list) # In[79]: sort_list is None # ## dict # * A Python dictionary called a hash map or an associated array # * Made of key value pairs # * Use curly braces `{}` and colons # In[86]: my_info = {"name" : "daniel", "age" : 30, "degree" : "phd", "skills" : ["R", "Python", "C++"]} # In[87]: my_info # In[88]: my_info["skills"] # In[89]: "name" in my_info # In[91]: my_info["colleges"] = ["UDSM", "TSU", "UNLV"] my_info # ## set # In[96]: set1 = {1, 2, 3, 4} set2 = {5, 6, 7, 8, 9, 4, 4} # In[97]: set1.union(set2) # In[99]: set1 | set2 # In[98]: set1.intersection(set2) # In[100]: set1 & set2 # ## Functions # In[104]: def my_func(): a = 4 b = 6 c = 8 return{"a" : a, "b" : b, "c" : c} # In[106]: my_func() # In[107]: states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda', 'south carolina##', 'West virginia?'] # In[109]: import re def clean_strings(strings): result = [] for value in strings: value = value.strip() value = re.sub('[!#?]', '', value) value = value.title() result.append(value) return result # In[110]: clean_strings(states) # ### lambda (anonymous) functions # A way of writing functions consisting of a single statement, the result of which is a return value # In[111]: anon_func = lambda x: x * 2 # In[113]: anon_func(2) # ## Files and the operation system # In[121]: path = "examples/segismundo.txt" f = open(path) # In[122]: lines = [x.rstrip() for x in f] lines # In[123]: f.close() # In[124]: with open(path) as f: lines = [x.rstrip() for x in f] # In[125]: lines # In[129]: with open(path) as f: lines = f.readlines() lines # In[ ]: