python基礎語法快速複習
阿新 • • 發佈:2022-05-18
◆版權宣告:本文出自胖喵~的部落格,轉載必須註明出處。
轉載請註明出處:https://www.cnblogs.com/by-dream/p/12895967.html
基本判斷
# -*- coding: utf-8 -*- # 變數初始化 i = 0 s = "abcde" j = [] k = {} # 基本判斷 if i == 0 and j is not None: print 'test1' elif k is None: print 'test2' else: print 'test3'
輸出
test1
迴圈
# 迴圈 s = "abcde"for word in s: print word for i in range(0, len(s)-1): print i, s[i]
輸出
a b c d e 0 a 1 b 2 c 3 d
三目運算子
# 三目表示式 k = 1 m = 2 print 'k' if k == 1 else 'm' print 'k' if m == 1 else 'm'
輸出
k m
字串處理
# 字串處理 s="ABCdefaa" print s.lower() print s.upper() print s[1:] print s.strip('a') print s.replace('a','z')
輸出
abcdefaa ABCDEFAA BCdefaa ABCdef ABCdefzz
字元、數字判斷
# 字元、數字判斷 class Test: def function(self, n): print n, n.isdigit(), n.isalpha(), n.isalnum() t = Test() t.function("123abc") t.function("123456") t.function("abcdef")
輸出
123abc False False True 123456 True False True abcdef False True True
數字處理
# -*- coding: utf-8 -*- import math # 數字處理 print '1<<2', 1<<2 print '1<<3', 1<<3 print '8>>2', 8>>2 # 平方 print pow(2,3) # 開方 print math.sqrt(36) print math.sqrt(25)
輸出
1<<2 4 1<<3 8 8>>2 2 8 6.0 5.0
列表
# list 當棧用 l = [] l.append('a') l.append('b') l.append('c') l.append('a') print l, len(l), l[0], l[len(l)-1] print l.pop() print l
輸出
['a', 'b', 'c', 'a'] 4 a a a ['a', 'b', 'c']
二維陣列
# 二維陣列 z = [[0 for column in range(3)] for row in range(2)] print z z[1][1] = 1 print z
輸出
[[0, 0, 0], [0, 0, 0]] [[0, 0, 0], [0, 1, 0]]
Map
# map m = {} m['bob'] = 18 m['jack'] = 20 print m, m.has_key('jack'), m.has_key('liming')
輸出
{'bob': 18, 'jack': 20} True False
堆
# -*- coding: utf-8 -*- from heapq import * # 堆 # (小頂堆) 每次pop出最小的值 hp = [ 9, 1, 8 ] # 堆化 heapify(hp) print hp print heappop(hp) print hp heappush(hp, 11) heappop(hp) print hp
輸出
[1, 9, 8] 1 [8, 9] [9, 11]