Python的10大最佳功能是什么?
生活随笔
收集整理的這篇文章主要介紹了
Python的10大最佳功能是什么?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
技巧 1:
在Python中反轉字符串
>>> a = "codementor" >>> print ("Reverse is",a[::-1]) Reverse is rotnemedoc技巧 2:
轉置矩陣
>>> mat = [[1, 2, 3], [4, 5, 6]] >>> zip(*mat) [(1, 4), (2, 5), (3, 6)]技巧 3:
將列表的所有三個值存儲在3個新變量中
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' >>> 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
技巧 7:
打印codecodecodecode mentormentormentormentormentor而不使用循環
>>> print ("code"*4+' '+"mentor"*5) codecodecodecode mentormentormentormentormento技巧 8:
a = [[1, 2], [3, 4], [5, 6]]將其轉換為單個列表,而不使用任何循環。
Output:- [1, 2, 3, 4, 5, 6]
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' >>> import itertools >>> list(itertools.chain.from_iterable(a)) [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]技巧 9:
檢查兩個詞是否是字謎
def is_anagram(word1, word2):"""Checks whether the words are anagrams.word1: stringword2: stringreturns: 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]
請記住,返回的列表中包含整數。不要使用多于一行的代碼。
>>> result = map(lambda x:int(x) ,raw_input().split()) 1 2 3 4 >>> result [1, 2, 3, 4]總結
以上是生活随笔為你收集整理的Python的10大最佳功能是什么?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python骚操作:动态定义函数
- 下一篇: 如何使用python numpy中的数组