OSDN Git Service

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