OSDN Git Service

Regular updates
[twpd/master.git] / python.md
1 ---
2 title: Python
3 category: Python
4 layout: 2017/sheet
5 ---
6
7 ### Tuples (immutable)
8
9     tuple = ()
10
11 ### Lists (mutable)
12
13     list = []
14     list[i:j]  # returns list subset
15     list[-1]   # returns last element
16     list[:-1]  # returns all but the last element
17     *list      # expands all elements in place
18     
19     list[i] = val
20     list[i:j] = otherlist  # replace ith to jth-1 elements with otherlist
21     del list[i:j]
22
23     list.append(item)
24     list.extend(another_list)
25     list.insert(index, item)
26     list.pop()        # returns and removes last element from the list
27     list.pop(i)       # returns and removes i-th element from the list
28     list.remove(i)    # removes the first item from the list whose value is i
29     list1 + list2     # combine two list    
30     set(list)         # remove duplicate elements from a list
31
32     list.reverse()    # reverses the elements of the list in-place
33     list.count(item)
34     sum(list)
35
36     zip(list1, list2)  # returns list of tuples with n-th element of both list1 and list2
37     list.sort()        # sorts in-place, returns None
38     sorted(list)       # returns sorted copy of list
39     ",".join(list)     # returns a string with list elements seperated by comma
40
41 ### Dict
42
43     dict = {}
44     dict.keys()
45     dict.values()
46     "key" in dict    # let's say this returns False, then...
47     dict["key"]      # ...this raises KeyError
48     dict.get("key")  # ...this returns None
49     dict.setdefault("key", 1)
50     **dict           # expands all k/v pairs in place
51
52 ### Iteration
53
54     for item in ["a", "b", "c"]:
55     for i in range(4):        # 0 to 3
56     for i in range(4, 8):     # 4 to 7
57     for i in range(1, 9, 2):  # 1, 3, 5, 7
58     for key, val in dict.items():
59     for index, item in enumerate(list):
60
61 ### [String](https://docs.python.org/2/library/stdtypes.html#string-methods)
62
63     str[0:4]
64     len(str)
65
66     string.replace("-", " ")
67     ",".join(list)
68     "hi {0}".format('j')
69     f"hi {name}" # same as "hi {}".format('name')
70     str.find(",")
71     str.index(",")   # same, but raises IndexError
72     str.count(",")
73     str.split(",")
74
75     str.lower()
76     str.upper()
77     str.title()
78
79     str.lstrip()
80     str.rstrip()
81     str.strip()
82
83     str.islower()
84     
85     /* escape characters */
86     >>> 'doesn\'t'  # use \' to escape the single quote...
87         "doesn't"
88     >>> "doesn't"  # ...or use double quotes instead
89         "doesn't"
90     >>> '"Yes," they said.'
91         '"Yes," they said.'
92     >>> "\"Yes,\" they said."
93         '"Yes," they said.'
94     >>> '"Isn\'t," they said.'
95         '"Isn\'t," they said.'
96
97 ### Casting
98
99     int(str)
100     float(str)
101     str(int)
102     str(float)
103     'string'.encode()
104
105 ### Comprehensions
106
107     [fn(i) for i in list]            # .map
108     map(fn, list)                    # .map, returns iterator
109     
110     filter(fn, list)                 # .filter, returns iterator
111     [fn(i) for i in list if i > 0]   # .filter.map
112
113 ### Regex
114
115     import re
116
117     re.match(r'^[aeiou]', str)
118     re.sub(r'^[aeiou]', '?', str)
119     re.sub(r'(xyz)', r'\1', str)
120
121     expr = re.compile(r'^...$')
122     expr.match(...)
123     expr.sub(...)
124
125 ## File manipulation
126     
127 ### Reading
128
129 ```py
130 file = open("hello.txt", "r") # open in read mode 'r'
131 file.close() 
132 ```
133
134 ```py
135 print(file.read())  # read the entire file and set the cursor at the end of file
136 print file.readline() # Reading one line
137 file.seek(0, 0) # place the cursor at the beginning of the file
138 ```
139
140 ### Writing (overwrite)
141
142 ```py
143 file = open("hello.txt", "w") # open in write mode 'w'
144 file.write("Hello World") 
145
146 text_lines = ["First line", "Second line", "Last line"] 
147 file.writelines(text_lines)
148
149 file.close()
150 ```
151
152 ### Writing (append)
153
154 ```py
155 file = open("Hello.txt", "a") # open in append mode
156 file.write("Hello World again")  
157 file.close()
158 ```
159
160 ### Context manager
161
162 ```py
163 with open("welcome.txt", "r") as file:
164     # 'file' refers directly to "welcome.txt"
165    data = file.read()
166
167 # It closes the file automatically at the end of scope, no need for `file.close()`.
168 ```