Python学习笔记记录
在codecademy巩固学习了下Python,好久没用了,顺便记录了24条学习笔记,有些零散,供参考。
1. String
***************************************************************************************************************
hello = “Hello”
- hello[0] = “H”
len(hello) hello的长度
hello.lower() = “hello”; You can use the lower() method to get rid of all the capitalization in your strings
hello.upper() = “HELLO”
str(2)=“2”
- string_1 = “Camelot" string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
2. Not and or 执行顺序
***************************************************************************************************************
def function_name(param) :
if condition:
elif condition:(if failed will go into elif)
else:
3. Lists and Dictionaries
***************************************************************************************************************
list_name[index], begin with 0,not 1!
赋值: list_name[index] = sth
list大小 len(list_name)
尾部增加集合元素 list_name.append(sth)
list slicing:slice = list_name[startIndex : endIndex] 取list_name第startIndex开始,包含第startIndex个元素,到endIndex个元素,不包含第endIndex个元素
list_name[:index]: 从头到index个元素,不包含第index个元素
list_name[index:]:从第index个元素到最后,包含第index个元素
list_name.index(元素), list_name.insert(index,元素), list_name.sort(), list_name.remove(元素), list_name.pop(index), del(list_name[index])
for variable in list_name:
#Do stuff!
dict_name = {key:value, key1:value1 …}
dict_name[new_key] = new_value
del dict_name[key_name]
for i in range(0, len(n)):
4. Float and Integer
***************************************************************************************************************
5 / 2
# 2
5.0 / 2
# 2.5
float(5) / 2
# 2.5
sum(list_name)
average(list_name)
range(stop)
range(start, stop)
range(start, stop, step)
Method 1 - for item in list:
for item in list:
print item
Method 2 - iterate through indexes:
for i in range(len(list)):
print list[i]
while/else ,for/else和 if/else 类似,区别是while的condition如果是false才能进入,如果while里有break,那就不会进入else。
5. For your strings:
***************************************************************************************************************
for c in thing:
print c
6. 逗号就是空格
***************************************************************************************************************
The , character after our print statement means that our next print statement keeps printing on the same line.
7. Counting as you go
***************************************************************************************************************
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index+1, item
8. Multiple lists
***************************************************************************************************************
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
print max(a,b)
zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
zip can handle three or more lists as well!
9. is_int
***************************************************************************************************************
def is_int(x):
if isinstance(x, int):
return True
elif x - int(x) == 0:
return True
else:
return False
10. 阶乘
***************************************************************************************************************
def factorial(x):
if x == 0:
return 1;
else:
return x * factorial(x-1)
11. reverse
***************************************************************************************************************
list_str=[]
def reverse(text):
for char in text:
list_str.append(char);
list_str.sort(cmp=None, key=None, reverse=True);//逆序
return "".join(list_str)
str = reverse(“abcd")
print str
//输出是dcba
sort函数:http://blog.csdn.net/dingyaguang117/article/details/7237596
12. censor
***************************************************************************************************************
def censor(text,word)://把text中的word变成*
text_list = text.split(" ")
for i in range(len(text_list)):
if text_list[i] == word:
text_list[i] = "*"*len(text_list[i])
return " “.join(text_list)
average = grades_sum(grades) / float(len(grades)) //结果是float,必须除数是float
13. Iterators for Dictionaries
***************************************************************************************************************
dict_name.items()
dict_name.keys(),dict_name.values()
dict 遍历
for key in dict_name:
print key, dict_name[key]
14. List Comprehension Syntax
***************************************************************************************************************
even_squares = [x**2 for x in range(1,11) if x % 2 ==0]
[4, 16, 36, 64, 100]
15. Omitting Indices
***************************************************************************************************************
to_five = ['A', 'B', 'C', 'D', 'E']
print to_five[3:]
# prints ['D', 'E']
print to_five[:2]
# prints ['A', 'B']
print to_five[::2]
# print ['A', 'C', ‘E']
my_list = range(1, 11) # List of numbers 1 - 10
print my_list[2:11:2] [1,3,5,7]
16. Reversing a List(List逆序输出)
***************************************************************************************************************
letters = ['A', 'B', 'C', 'D', 'E']
print letters[::-1]
['E', 'D', 'C', 'B', ‘A'].
17. List slicing not List Comperhension
***************************************************************************************************************
to_21 = range(22)[1:22:1]
print to_21
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
odds = to_21[::2]
print odds
//[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
middle_third = to_21[7:14]
print middle_third
//[8, 9, 10, 11, 12, 13, 14]
18. Anonymous Functions
***************************************************************************************************************
lambda x: x % 3 == 0
功能一致:
def by_three(x):
return x % 3 == 0
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
//[0, 3, 6, 9, 12, 15]
19. List Slicing
***************************************************************************************************************
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-1][0:len(garbled):2]
print message
//I am the secret message!
20. Bitwise operations
print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT
0
10
0
13
38
-89
8's bit 4's bit 2's bit 1's bit
1 0 1 0
8 + 0 + 2 + 0 = 10
one = 0b1
two = 0b10
three = 0b11
four = 0b100
five = 0b101
bin(i) i的二进制
x=int(“i”,2)表示x=二进制的i转换成十进制
21. 移动
***************************************************************************************************************
# Left Bit Shift (<<)
0b000001 << 2 == 0b000100 (1 << 2 = 4)
0b000101 << 3 == 0b101000 (5 << 3 = 40)
# Right Bit Shift (>>)
0b0010100 >> 3 == 0b000010 (20 >> 3 = 2)
0b0000010 >> 2 == 0b000000 (2 >> 2 = 0)
22. BIT of This AND That
***************************************************************************************************************
a: 00101010 42
b: 00001111 15
===================
a & b: 00001010 10
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
23. OR
***************************************************************************************************************
a: 00101010 42
b: 00001111 15
================
a | b: 00101111 47
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
24. This XOR That?
***************************************************************************************************************
a: 00101010 42
b: 00001111 15
================
a ^ b: 00100101 37
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
NOT operator (~) :加一变负号
判断第四位是否为1,是则返回on,否返回off
fourth = 0b1000
def check_bit4(input):
if input & fourth > 0:
return "on"
else:
return “off"
25. class
***************************************************************************************************************
class Point3D(object):
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1,2,3)
print my_point //(1,2,3)
24. File
***************************************************************************************************************
“\n" —回车
f = open("output.txt", “w")
You can open files in write-only mode ("w"), read-only mode ("r"), read and write mode ("r+"), and append mode ("a", which adds any new data you write to the file to the end of the file).
Python doesn't flush the buffer,所以每次确定写入成功地语句就是file_name.close()
with 和 as 关键字
with open("file", "mode") as variable:
# Read or write to the file