技巧1
字符串倒置
>>> a = "codementor">>> print "Reverse is",a[::-1]
倒置之后的結果是“rotnemedoc”。
技巧2
轉置矩陣(transposing a matrix)(譯者注:把矩陣A的行換成相應的列,得到的新矩陣稱為A的轉置矩陣)
>>> mat = [[1, 2, 3], [4, 5, 6]]>>> zip(*mat)
[(1, 4), (2, 5), (3, 6)]
技巧3
a = [1,2,3]
將上述列表中的三個值分別存儲在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
list1 = ['a', 'b', 'c', 'd']list2 = ['p', 'q', 'r', 's']
編寫可以打印出下面結果的代碼
ap
bq
cr
ds>>> for x, y in zip(list1,list2):... print x, y ... a p b q c r d 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
判斷兩個單詞是否是回文單詞(anagram)?
def is_anagram(word1, word2):"""Checks whether the words are anagrams. 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]。
記住,返回列表中的元素是整型數。代碼不要超過一行。
>>> result = map(lambda x:int(x) ,raw_input().split())1 2 3 4>>> result [1, 2, 3, 4]
長按二維碼識別關注,您的支持是我們最大的動力。
公眾號:測試夢工廠
QQ一群:300897805