OSDN Git Service

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