Lecture 3

  • 2**3=8 (it means pow in Python)
  • x,y=y,x just change value of x and y
  • literal—10 variable—X statement— x=y expression— x*y
  • binary decimal hex
  • Negative numbers left most—sign bit
  • type(*) show the type of *
  • 1000 0000 -> -1 1111 1111 -> -128

Python

.find('a') the first 'a' apppear in the srting
.rfind('a') the last 'a' appear in the string
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。
.replace( '  ','    ')
.count('  ')
.swapcase()
.lower()
.upper()

interpreter — 解释器

python print格式化输出。

\1. 打印字符串

print ("His name is %s"%("Aviad"))

效果: img

2.打印整数

print ("He is %d years old"%(25))

效果: img

3.打印浮点数

print ("His height is %f m"%(1.83))

效果: img

4.打印浮点数(指定保留小数点位数)

print ("His height is %.2f m"%(1.83))

效果: img

NOTICE

data = list(range(-10,10))
print(data)
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [12]:

data[1:-1]

Out[12]:

[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]

In [13]:

data[:-1]

Out[13]:

[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]

A neat trick—to reverse a list, index it from beginning to end and then count backwards:

In [15]:

data[::-1]

Out[15]:

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6

my_list.remove

my_list.append

Strings are immutable; we cannot change its

content without creating a new string

s = ‘strang’
s[3] = ‘i’

s = s[:3] + ‘i’ + s[4:]

#nope
#correct
x = [4,1,2,4]
x[3] = -2
x.append(5)
x.sort()

del x[1]

#item assignment
#add an item to the end
#sort items by value

#delete an item

The range function returns an iteratorcontaining integers in a specified range

• range can be casted as a list– list(range(1, 10))

​ ​ ​ ​ ​ ​ ​ ​ ​ Two arguments:

– (optional) the starting value (inclusive) otherwise —>0 list(range(10)) – The ending value (exclusive)

​ ​ ​ ​ s[:4] not consist 4

period -> .

print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 

swapcase

capitalize

​ ​ ​ Immutable types: value of x is copied in memory and assigned to y (copy by value)

​ ​ Mutable type: the new variable y refers to the same memory location of the value that x refers to (copy by reference, or shallow copy)

y is aliase to x

differnece

append extend

del a[5]

a.remove('4')

a.pop()

d.keys()

d.values()

list(d.keys())

list(d.values())

Mutabilitycausesliststoworkdifferentlywhenpassed to a function

• Canbechangedwithinafunction• Veryuseful

   def fun(q,i):
      q.append(i)

   a = []
   for i in range(10)

      fun(a,i)
   print(a)

jwt

b = a differ from b = a[:]

the former is calling by refer

the later is calling by value

myfile = open('filename')
for line in myfile.read():
	...
myfile = open('woedk', 'r')
my = myfile.readlines()
my -> a list

write file

myfile = open('...', 'w')
myfile.write('.....')
myfile.close()

a ->append data to the end without erease data...

myfile = open('...','a')

Sort

l.sort(reverse=True) #Change l
sorted(l, reverse=True) #Doesn't change l, just return a value.				

​ ​ Sort a dict by value

​ d = [‘one’:1, ‘two’:2, ‘three’:3]sorted(d, key=lambda x:d[x])

d = [‘one’:1, ‘two’:2, ‘three’:3]

t = list(d.items())

sorted(t, key=lambda x:x[1])

>>> [(‘one’,1), (‘two’,2), (‘three’,3)]

sorted(t, key=lambda x:x[0])

>>> [(‘one’,1), (‘three’,3), (‘two’,2)]

Open

– Accept as argument a file name – Access mode: ‘r’, ‘w’, ‘a’ – Returns a file data type

​ ​ ​ ​ ​ ​ ​ ​ ​ file type

​ ​ ​ ​ file

– A iterable for the opened file – file.read() returns a string of the entire file – file.readlines() returns a list – file.close()

Read a csv

myfile = opne('auto.csv')
rows = myfile.readlines()
for row in rows:
  col = row.strip().split(',')
  col[0],col[1].....
from csv import DictReader

reader = DictReader(open('autos.csv'))
print(type(reader))
for row in reader:
	print(type(row))
	print(row['Model'], row['Price'])

​ ​ ​ ​ ​ ​ ​ ​ ​ Year, Make, Model, Price

2007, Chevrolet, Camaro, 5000.00 2010, Ford, F150, 8000.00 2011,Dodge,Grand Caravan,7500.00

​ ​ ​ ​

list(dict.items()) contain tuple

zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。具体意思不好用文字来表述,直接看示例:

x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
print xy

运行的结果是:

[(1, 4), (2, 5), (3, 6)]

x = [1, 2, 3]

y = [4, 5, 6]

z = [7, 8, 9]

xyz = zip(x, y, z)

print xyz

运行的结果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

从这个结果可以看出zip函数的基本运作方式。

for a,b in zip(x,y)
# another way
for i,item in enumerate( my_list ):

    print( '%s is the %sth item.' % (item,i) )

​ key,value

# one way
for i in 'ABCD':

    for j in 'ABCD':
        if i == j:

            continue
        print( i, j )

# another way
from itertools import permutations
for doublet in permutations( 'ABCD',2 ):

    print( doublet )

全排列combinations和permutations函数

python的对象引用

1). python不允许程序员选择采用传值还是传引用。Python参数传递采用的肯定是“传对象引用”的方式。实际上,这种方式相当于传值和传引用的一种综合。如果函数收到的是一个可变对象(比如字典或者列表)的引用,就能修改对象的原始值——相当于通过“传引用”来传递对象。如果函数收到的是一个不可变对象(比如数字、字符或者元组)的引用,就不能直接修改原始对象——相当于通过“传值'来传递对象。 2). 当人们复制列表或字典时,就复制了对象列表的引用同,如果改变引用的值,则修改了原始的参数。 3). 为了简化内存管理,Python通过引用计数机制实现自动垃圾回收功能,Python中的每个对象都有一个引用计数,用来计数该对象在不同场所分别被引用了多少次。每当引用一次Python对象,相应的引用计数就增1,每当消毁一次Python对象,则相应的引用就减1,只有当引用计数为零时,才真正从内存中删除Python对象。

一、 如何切片和索引:

import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]

# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print a[0, 1]   # Prints "2"
b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
print a[0, 1]   # Prints "77"

二、切片和索引容易搞混的地方(维度)

import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row_r1 = a[1, :]    # Rank 1 view of the second row of a  
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
print row_r1, row_r1.shape  # Prints "[5 6 7 8] (4,)"  一维
print row_r2, row_r2.shape  # Prints "[[5 6 7 8]] (1, 4)" 二维

# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print col_r1, col_r1.shape  # Prints "[ 2  6 10] (3,)" 一维
print col_r2, col_r2.shape  # Prints "[[ 2]
                            #          [ 6]
                            #          [10]] (3, 1)" 二维

三、索引为数值时

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

# An example of integer array indexing.
# The returned array will have shape (3,) and 
print a[[0, 1, 2], [0, 1, 0]]  # Prints "[1 4 5]"

# The above example of integer array indexing is equivalent to this:
print np.array([a[0, 0], a[1, 1], a[2, 0]])  # Prints "[1 4 5]"

# When using integer array indexing, you can reuse the same
# element from the source array:
print a[[0, 0], [1, 1]]  # Prints "[2 2]"  索引为(0,1) (0,1)

# Equivalent to the previous integer array indexing example
print np.array([a[0, 1], a[0, 1]])  # Prints "[2 2]"
import numpy as np

# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])

print a  # prints "array([[ 1,  2,  3],
         #                [ 4,  5,  6],
         #                [ 7,  8,  9],
         #                [10, 11, 12]])"

# Create an array of indices
b = np.array([0, 2, 0, 1])

# Select one element from each row of a using the indices in b
print a[np.arange(4), b]  # Prints "[ 1  6  7 11]"

# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10

print a  # prints "array([[11,  2,  3],
         #                [ 4,  5, 16],
         #                [17,  8,  9],
         #                [10, 21, 12]])

四、索引为布尔型时

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

bool_idx = (a > 2)  # Find the elements of a that are bigger than 2;
                    # this returns a numpy array of Booleans of the same
                    # shape as a, where each slot of bool_idx tells
                    # whether that element of a is > 2.
            
print bool_idx      # Prints "[[False False]
                    #          [ True  True]
                    #          [ True  True]]"

# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print a[bool_idx]  # Prints "[3 4 5 6]"

# We can do all of the above in a single concise statement:
print a[a > 2]     # Prints "[3 4 5 6]"