技巧 #1
字串翻轉
>>> a = "codementor"
>>> print "Reverse is",a[::-1]
翻轉后的結果為 rotnemedoc
PS:很多人在學習Python的程序中,往往因為遇問題解決不了或者沒好的教程從而導致自己放棄,為此我整理啦從基礎的python腳本到web開發、爬蟲、django、資料挖掘等【PDF等】需要的可以進Python全堆疊開發交流.裙 :一久武其而而流一思(數字的諧音)轉換下可以找到了,里面有最新Python教程專案可拿,不懂的問題有老司機解決哦,一起相互監督共同進步
技巧 #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
>>> x
1
>>> y
2
>>> z
3
技巧 #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 p
b q
c r
d s
技巧 #6
僅用一行代碼實作兩個變數的交換
>>> a=7
>>> b=5
>>> b, a =a, b
>>> a
5
>>> b
7
技巧 #7
不使用回圈,輸出 "codecodecodecode mentormentormentormentormentor"
>>> print "code"*4+' '+"mentor"*5
codecodecodecode 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 Counter
def 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]
總結:很多人在學習Python的程序中,往往因為遇問題解決不了或者沒好的教程從而導致自己放棄,為此我整理啦從基礎的python腳本到web開發、爬蟲、django、資料挖掘等【PDF等】需要的可以進Python全堆疊開發交流.裙 :一久武其而而流一思(數字的諧音)轉換下可以找到了,里面有最新Python教程專案可拿,不懂的問題有老司機解決哦,一起相互監督共同進步本文的文字及圖片來源于網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/193606.html
標籤:Python
上一篇:python練習——第2題
