09.07 悄悄告訴你:10 個 Python 初學者必知編碼小技巧!

悄悄告訴你:10 個 Python 初學者必知編碼小技巧!

技巧 #1字符串翻轉

a = "codementor">>> print "Reverse is",a[::-1]翻轉後的結果為 rotnemedoc

技巧 #2

矩陣轉置

mat = [[1, 2, 3], [4, 5, 6]]>>> zip(*mat)[(1, 4), (2, 5), (3, 6)]

技巧 #3

a = [1,2,3]

將列表中的三個元素分拆成三個變量

a = [1, 2, 3]>>> x, y, z = a>>> x1>>> y2>>> z3

技巧 #4

a = ["Code", "mentor", "Python", "Developer"]

將字符串列表拼接成一個字符串

print " ".join(a)Code mentor Python Developer

技巧 #5

List 1 = ['a', 'b', 'c', 'd']

List 2 = ['p', 'q', 'r', 's']

編寫 Python 代碼,實現下面的輸出

ap

bq

cr

ds

for x, y in zip(list1,list2):... print x, y...a pb qc rd s

技巧 #6

僅用一行代碼實現兩個變量的交換

a=7>>> b=5>>> b, a =a, b>>> a5>>> b7

技巧 #7

不使用循環,輸出 "codecodecodecode mentormentormentormentormentor"

print "code"4+' '+"mentor"5codecodecodecode mentormentormentormentormentor

技巧 #8

a = [[1, 2], [3, 4], [5, 6]]

不使用循環,將其轉變成單個列表

輸出:- [1, 2, 3, 4, 5, 6]

import itertools>>> list(itertools.chain.from_iterable(a))[1, 2, 3, 4, 5, 6]

技巧 #9

檢查一個單詞和另一個單詞是否只是字母順序不同

def is_anagram(word1, word2): """檢查一個單詞和另一個單詞是否只是字母順序不同 word1: string word2:string returns: boolean """

將上面的函數補充完畢,以檢查一個單詞和另一個單詞是否只是字母順序不同

from collections import Counterdef is_anagram(str1, str2): return Counter(str1) == Counter(str2)>>> is_anagram('abcd','dbca')True>>> is_anagram('abcd','dbaa')False

技巧 #10

從字符串輸入中獲取值

對於輸入數據 1 2 3 4 我們希望得到列表 [1, 2, 3, 4] 。

請注意,列表中的元素都是 int 類型,且只能使用一行代碼。

result = map(lambda x:int(x) ,raw_input().split())1 2 3 4>>> result[1, 2, 3, 4]

加vx:tanzhouyiwan 小編免費分享Python學習資料供大家學習哦哦!

悄悄告訴你:10 個 Python 初學者必知編碼小技巧!


分享到:


相關文章: