Python的小技巧

2018-05-09  本文已影响12人  klory
if xxx...:
    blabla
elif xxx...:
    blabla...
else:
    blabla...
alist = ['a', 'd', 'f']
alist[1:1] = ['b', 'c']  # [`a`, 'b', 'c', 'd', 'f']
print alist
alist[4:4] = ['e']  # [`a`, 'b', 'c', 'e', 'd', 'f']
print alist
a = 'banana'
b = 'banana'
print(a==b) #True
print(a is b)   #True
print("next part...\n")

aList = ['1', 1]
bList = ['1', 1]
print(aList == aList)   #True
print(aList is bList)   #False
bList[1] = 'haha'
print(aList)    #['1', 1]
print('next part...\n')
alist = [4,2,8,6,5]
blist = alist
print(alist == blist)   #True
print(alist is blist)   #True
blist[3] = 999
print(alist)    #[4, 2, 8, 999, 5],这里改的是blist,alist也跟着变了

# 如果要深拷贝数组:
blist = alist[:]
print(alist == blist)   #True
print(alist is blist)   #False

# 字典的话请使用内部函数copy
acopy = opposites.copy()
acopy['right'] = 'left'  # does not change opposites
filename= "yourfile.txt"
fileref = open(filename,"r")
for lin in fileref: # 比readlines要好,因为不需要一次读取整个文件
    ## operations on lin
fileref.close() 
value = 10
def f(x = value):
  print("x is:", x)

value = 1
f() # x is 10
def f(a, L=[]):
        L.append(a)
        return L
    
print f(1)
print f(2)
print f(3)
print f(4, ["Hello"])
print f(5, ["Hello"])
t = (5,)
print type(t)

x = (5)
print type(x)
上一篇下一篇

猜你喜欢

热点阅读