with open(MYFILE) as f:
for i, line in enumerate(f):
line = line.rstrip() # remove tailing '\n'
line = line.split("\t")
if i == 1:
print line
if line[0] == "MYSTRING":
print line
将文件读入Dictionary
1
2
3
4
5
6
7
8
9
d = {}
with open(MYFILE) as f:
for line in f:
line = line.rstrip() # remove tailing '\n'
(key, val) = line.split("\t")
d[key] = val
for i in d:
print i, d[i]
读取网面内容
1
2
3
4
5
6
7
8
importurllib2user_agent='Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'headers={'User-Agent':user_agent}request=urllib2.Request("https://url.com",None,headers)response=urllib2.urlopen(request)page_content=response.read()response.close()
Non-greedy match: “?”
Reverse a string
string[::-1]
Reverse a list
list.reverse()
list
Sort a list
print list.sort()
sorted(list)
将string中的值分别赋予给不同的变量
string = "abc,123"
a,b = string.split(',')
将list中的值分别赋予给不同的变量
list = [1, 2, 3]
a, b, c = list
使用空变量_
list = [1, 2, 3, 5, 8, 0]
a, _, c, d, _ = list [1:] # d = 8
将list中的值组合成一个string
1
2
3
4
list = ["a","b","c"]
print " ".join(list) # 'a b c'
d = "".join(list) # 'abc'
e = "".join((list1, list2, list3)) # needs two ()
执行完后休眠一定时间 (1s - 10s)
1
2
3
4
from random import randint
from time import sleep
sleep(randint(1,10))
city_code_dict = {
'HNL': 'Honolulu',
'ITO': 'Hilo',
'LHR': 'London/Heathrow',
'ARN': 'Stockholm/Arlanda',
'HKG': 'Hong Kong',
'YYZ': 'Toronto',
'CDG': 'Paris/Charles de Gaulle',
'NRT': 'Tokyo/Narita',
'GCM': 'Grand Cayman BWI',
'CUR': 'Curacao Netherland Antilles' }
codelist = ['HNL', 'ITO', 'LHR', 'LGA', 'GCM', 'MSY']
codes1 = (code for code in codelist if code in city_code_dict)
for code in codes1:
print code
codes2=[code for code in codelist if code not in city_code_dict]
print codes2
print set(codelist) - set(city_code_dict.keys())
Class 建立
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class BankAccount(object):
def __init__(self, name = None, balance = 99, type = None):
self.name = name
self.balance = balance
self.type = type
## function inside class
def cost(self, amount):
self.balance -= amount
myAccount = BankAccount(name= 'A', balance=399, type='saving')
print myAccount.type # saving
myAccount.cost(33)
print myAccount.balance # 366
myAccount.year = 5 # add another attribute
print myAccount.__dict__ # {'balance': 366, 'type': 'saving', 'name': 'A', 'year': 5}
Print tailing comma
for num in range(1,4):
print num
print num, # 1 2 3
Pickle to store and re-create dictionaries
import pickle
with open('outfile.pkl', 'wb') as outfile:
pickle.dump(your_dict, outfile)
new_dict = {}
with open('outfile.pkl', 'rb') as infile:
new_dict = pickle.load(infile)
Import module and use its function
import math
math.log(2)
import math as mh
mh.log(2)
from math import *
log(2)
Check module functions and help
dir(math)
help(doc)
help(math.log)
math.__doc__
Install Miniconda via bash script doesnot need admin
And you can install Python3 from it
conda list
conda install --name <name>
pip install <name>
print("-".join["a", "b", "c"])
print("This is me".replace("me", "you"))
print("This is me".startWith("This"))
print("This is me".endWith("you."))
print("This is me".upper()) # lower()
print("a,b,c".split(","))