help()函数与dir()函数都是帮助函数:
help()函数能够提供详细的帮助信息,dir()函数仅是简单的罗列可用的方法。
基础数据类型:数值型、布尔型和字符串型。
数值型数据的计算方法:
加 x+y
减 x-y
乘 x*y
除 x/y
幂次方 x**3
加等 x += 2 在x原有值的基础上再加2
减等 x -= 2 在x原有值的基础上减2
字符串类型用单引号或双引号引起,引号内的内容即为字符串类型(str)。
s1 = 'hello world'
s2= "hello world"
len(s1) = 11
long_str = ' I am a teacher. '
#去掉字符串左右两边的空格
long_str.strip() -> 'I am a teacher.'
#去掉字符串左边的空格
long_str.lstrip() -> 'I am a teacher. '
#去掉字符串右边的空格
long_str.rstrip() -> ' I am a teacher.'
#将字符串中的teacher替换为student
long_str.strip().replace('teacher', 'student') ->I am a student.
num_str = '123456'
num_str.isdigit() #判断变量是否为数值型变量
字符串切片
str = 'hello'
#str 01234
#str -1-2-3-4-5
str[1:4] -> 'ell' #序数从0开始,右区间为开区间
str[1:] -> 'ello'
str[:3] -> 'hel'
#逆序数
s[-5:] -> 'hello'
s[-4:-1] -> 'ell'
格式化输出
num_s = 100
num_t = 3
test_str = 'hello'
text = 'there are %d students in the classroom and %s' %(num_s, test_str)
text -> 'there are 100 students in the classroom and hello'
# %d格式化输出数字,%s格式化输出字符串, 括号内的参数按语句中对应的顺序。
s = 'hello world hello bigdata hello China'
s.split(' ') -> ['hello', 'world', 'hello', 'bigdata', 'hello', 'China']
#以空格将文本拆分为列表
score = 59
if score > 90:
print 'very good.'
elif score > 85:
print 'good.'
elif socre > 70:
print 'just so so.'
else:
print 'not so good'
# if--elif--else
# 每个判断语句写完后记得加冒号":"
A = True
B = False
A and B = False
A or B = True
(not A) or B = False
string_list = ['this', 'is', 'a', 'string']
len(string_list) = 4 #len()函数计算列表中元素的个数
string_list[1:3] -> ['is', 'a'] #列表的切片,同字符串的切片操作类似
列表中的元素没有类型限制,不同数据类型可以添加到同一个列表中。
mass = ['this', 'is', 'good', 3.14, 10]
#用for循环输出list元素的数据类型
for item in mass:
print type(item)
#用索引号index输出个性化结果
for index in range(5)
if index % 2 == 0: #索引号为偶数
print mass[index]
#用while循环(注重于结束的条件)
index = 0
while index < 2:
print mass[index]
index += 1
append与extend的区别
append可将任何对象添加到list中,甚至包括list。
extend只会将list中的元素添加进去。
sort与sorted的区别
sort()函数改变列表本身的顺序
sorted()函数不改变列表本身的顺序
高级排序
num_list = [1, 2, 3, 4, 5, 6, 7]
print sorted(num_list, reverse = True) #逆序排列 ->[7, 6, 5, 4, 3, 2, 1]
a = ['aa', 'bbbbb', 'ccc', 'dddd']
print sorted(a, key = len) #按字符串长度排列 ->['bbbbb', 'dddd', 'ccc', 'aa']
字典的查找速度较列表要快很多,原因是字典采用哈希算法(hash),即一个key对应一个value,使用花括号”{}”表示。
Dict = {key1: value1, key2: value2, key3: value3}
pets = {'dogs':3, 'cats':2, 'birds':4}
print pets['dogs'] #查找键值时使用中括号"[]" ->3
if 'cats' in pets:
print 'I have ' + str(pets['cats']) +'cats.' #只有字符串才能用"+"号连接,所以pets['cats']返回的值必须用str()函数转换为字符串。 ->I have 2 cats.
#for循环遍历字典
for pet in pets:
print 'I have ' + str(pets[pet]) + pet -> I have 3 dogs
I have 2 cats
I have 4 birds
#只想取出key
pets.keys() #会得到由键值组成的列表对象
sum(pets.keys()) #会得到列表中所有数字的加总和
#从字典中成对取出数据
for (pet, num) in pets.items(): #字典中的每一个元素都是一对键值对。
print pet, '=' ,num ->dogs = 3
cats = 2
birds = 4
#字典添加新的键值对
pets['ducks'] = 5
#字典删除键值对
del pets['ducks']
in_file = 'shanghai.txt'
for line in open(in_file):
print line.strip().splite(" ")
#使用"for line in open(file):"这种方式打开的文件不需要关闭句柄。
#strip()函数去除了每个段落前后的空格
#splite(" ")函数将每个段落中的单词以空格作为分隔符拆分为单个的列表元素。
#最后的拆分结果,每个段落组成一个列表,每个段落中的单词成为对应列表中的一个元素
#选用字典作为容器
words_count = {} #创建一个空字典
for line in open('shanghai.txt'):
words = line.strip().splite(" ") #对文本做处理,去掉段落前后的空格,并以空格作为分隔符拆分段落中的单词,构建列表。
for word in words:
if word in words_count:
words_count[word] += 1 #如果字典中存在该单词,对应的值+1
else:
words_count[word] = 1 #如果字典中不存在该单词,在字典中添加一个新的键值对。
#字典里存储的是词和词频
for word in words_count:
print word, words_count[word] #使用for循环遍历并输出字典中的单词和词频
定义函数要用下面的形式:
def 函数名(函数参数):
函数内容
例如:
def add_num(x,y):
return x+y
add_num(3, 4)
->7
def my_func(list_x):
new_list = []
for item in list_x:
new_list.append(item**3)
return new_list
my_test = [1, 2, 3, 4, 5]
my_func(my_test)
->[1, 8, 27, 64, 125]
#定义函数自动读取文件并输出文件中的单词和词频
def count_words(in_file, out_file):
words_count = {}
#对每一行去前后两端的空格,用单词间的空格作为分隔符分拆单词,采用字典记录
for line in open(in_file):
for word in line.strip().rstrip('.').splite(" "):
if word in words_count:
words_count[word] += 1
else:
words_count[word] + 1
# 打开文件并写入结果
out = open(out_file, 'w') # 'w' 代表 'w'riting,这种打开文件的方式最后需要关闭句柄。
for word in words_count:
out.write(word + "#" + str(words_count[word]) + "\n") #将单词和词频用一定的格式写入文件
out.close #关闭句柄
#调用函数
count_words('shanghai.txt', 'words_count.txt')
当需要对于列表中的每一个元素做相同的操作时,可以采用list comprehension方法。
[需要对item做的操作 for item in list (可选部分:对item的限制条件)]
test_list = [1, 2, 3, 4]
[item**3 for item in test_list]
->[1, 8, 27, 64]
['num_' + str(item) for item in test_list]
->['num_1', 'num_2', 'num_3', 'num_4']
[item**3 for item in test_list if item % 2 ==0] # 对列表中为偶数的元素做立方处理,并输出新的列表
->[8, 64]
[item**4 for item in test_list if item % 2 ==0 and item > 3] # 对列表中为偶数且大于3的元素乘4次方,并输出新的列表。
->[256]