Python

Python

注释

#coding:utf-8    当代码中(包含注释)要出现中文的时候,需要加这一行
#Say something NOT IMPORTANT

变量

Python不是必须要用int, float, doubledefine变量
当然,如果用关键词定义之后,该变量的类型将不可变。
反之,类型可变。

布尔运算

短路计算。

  • 在计算 a and b 时,如果 a 是 False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a 是 True,则整个计算结果必定取决与 b,因此返回 b。
  • 在计算 a or b 时,如果 a 是 True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;如果 a 是 False,则整个计算结果必定取决于 b,因此返回 b。

所以,Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。
够懒!!

a = 'python'
print 'hello,', a or 'world'

b = ''
print 'hello,', b or 'world'

# why?
# try false or i

print 'hahaha' and a

output >>
hello, python
hello, world
python

List

创建List

classmates = ['Michael', 'Bob', 'Tracy']```

###List的访问
与数组相同,例如```classmate[0] = Michael```,此外,List还可以倒序访问,例如```classmate[-1] = Tracy```

###Add
```python
#Say something NOT IMPORTANT
classmate.append("new_classmate")    #Add in the END
classmate.insert(1,"new_classmate")    #Add in the 2nd location

Delete

#Say something NOT IMPORTANT
classmate.opp()    #Delete the FINAL
classmate.insert(1)    #Delete the 2nd

Replace

#Say something NOT IMPORTANT
classmate[0] = 'You'
classmate[-1] = 'Me'

Tuple

tuple一旦创建就不能修改

Create

Like List

classmates = ('Michael', 'Bob', 'Tracy')
className = ('Metoo',)    #Create single element

Variable Tuple

t = ('a', 'b', ['A', 'B'])
L = t[2]
L[0] = 'hha'
L[1] = 'lla'

tuple一旦创建就不能修改,但是List却可以修改

IF

#Say something NOT IMPORTANT
score = 85

if score >= 90:
    print 'excellent'
elif score>= 80:
    print 'good'
elif score >= 60:
    print 'passed'
else:
    print 'failed'

Loop

For

#Sum of L

L = [75, 92, 59, 68]
sum = 0.0
for score in L:
    sum = sum + score
print sum

While

# coding=utf-8
#求100以内奇数和
sum = 0
x = 1
while x < 100:
    sum = sum +1
    x = x + 2
print sum

break & continue

#coding=utf-8
#求100以内奇数和

sum = 0
x = 0
while True:
    x = x + 1
    if x > 100:
        break    #跳出整个while循环
    
    if x%2 == 0:
        continue    #跳出本次循环,继续下次循环
    
    sum = sum + x
print sum

Dict

特点

  1. 查找速度快,无论dict有10个元素还是10万个元素,查找速度都一样。 而list的查找速度随着元素增加而逐渐下降。不过dict的查找速度快不是没有代价的,dict的缺点是占用内存大,还会浪费很多内容,list正好相反,占用内存小,但是查找速度慢。
  2. dict是按 key 查找,所以,在一个dict中,key不能重复
  3. 存储的key-value序对是没有顺序的!
  4. 作为 key 的元素必须不可变 Python的基本类型如字符串、整数、浮点数都是不可变的,都可以作为 key。但是list是可变的,就不能作为 key。

Add & update

d = {
    95: 'Adam',
    85: 'Lisa',
    59: 'Bart'
}
d[72] = 'Paul'    #add
d[95] = 'Mary'    #update
print d

Set

特点

  1. set 持有一系列元素,这一点和 list 很像,但是set的元素没有重复,而且是无序的,这点和 dict 的 key很像。
  2. set内部存储的元素是无序的。
  3. set不能包含重复的元素
s = set(['A', 'B', 'C', 'C'])
print s,len(s)

>>output
set(['A', 'C', 'B']) 3

访问

由于set存储的是无序集合,所以我们没法通过索引来访问。
所以用in操作符访问
例:

s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
print 'adam' in s
print 'Adam' in s

>>output
Fasle
True

Update

L = ['a','b','c']
s = set(L)
s.add('d')
s.remove('a')
print s

>>output
set(['c', 'b', 'd'])

Function

#coding=utf-8
#调用系统函数
abs(-20)
sum(L)    #接受一个List,返回List各元素的和

#自定义
def func1(a,b):
    #coding...
    return a;

#调用库
import math

def num_sqrt(x)
    return math.sqrt(x)

默认参数

#coding=utf-8
#如果有其他参数传入,则默认参数置于最后
def greet(a = ''):
    if a == '':
        print 'Hello,world.'
    else:
        print 'Hello,',a,'.'

greet()
greet('Bart')

可变参数

#coding = utf-8
#请编写接受可变参数的 average() 函数。
def average(*args):
    if len(args) == 0:
        return 0.0
    else:
        return (sum(args)*1.0/len(args))    ## *1.0真乃神作

print average()
print average(1, 2)
print average(1, 2, 2, 3, 4)

>>output
0.0
1.5
2.4

切片

List

#coding=utf-8
#range()函数可以创建一个数列:
#>>> range(1, 101)
#[1, 2, 3, ..., 100]
#
#请利用切片,取出:
#1. 前10个数;
#2. 3的倍数;
#3. 不大于50的5的倍数。

L = range(1, 101)

print L[0:10]        #从L[0]开始,取前十
print L[2::3]         #从L[2]到最后,隔3取
print L[4:50:5]    #从L[4]到50,隔5取

>>output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

倒序切片

#coding=utf-8
#利用倒序切片对 1 - 100 的数列取出:
#最后10个数;
#最后10个5的倍数。

L = range(1, 101)
print L[-10:]
print L[4::5][-10:]    #切片可嵌套,先取5的倍数,再取后十个

>>output
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
[55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

同样,对字符串也可以切片!!
例如:

>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[-3:]
'EFG'
>>> 'ABCDEFG'[::2]
'ACEG'

'''
字符串有个方法 upper() 可以把字符变成大写字母:
>>> 'abc'.upper()
'ABC'
但它会把所有字母都变成大写。请设计一个函数,它接受一个字符串,然后返回一个仅首字母变成大写的字符串。
'''
#code
def firstCharUpper(s):
    return (s[:1].upper()+s[1:])    #注意:Python可以用 ‘+’ 来连接字符串,如果没有加号,将输出 ‘H’,‘ello’

print firstCharUpper('hello')
print firstCharUpper('sunday')
print firstCharUpper('september')

>>output
Hello
Sunday
September

迭代

'''
zip()
zip()函数可以把两个 list 变成一个 list:
>>> zip([10, 20, 30], ['A', 'B', 'C'])
[(10, 'A'), (20, 'B'), (30, 'C')]
'''

#**注意**
#python3中zip需要包含在List中,即

list1 = ['a','b','c']
list2 = [1,2,3]

dict = list(zip(list1,list2))
原文地址:https://www.cnblogs.com/pualus/p/7930286.html