1,判斷一個字元串中的每一個字母是否都在另一個字元串中,可以利用集合的特性來解,集合的元素如果存在,再次更新(update) 是添加不進集合的,那麼集合的長度還是跟原來一樣,如果添加進去,集合長度就會增加 2,如果是多個字元呢? 3,統計出現次數最多的字元 這裡有個lambda表達式, key指定按 ...
1,判斷一個字元串中的每一個字母是否都在另一個字元串中,可以利用集合的特性來解,集合的元素如果存在,再次更新(update) 是添加不進集合的,那麼集合的長度還是跟原來一樣,如果添加進去,集合長度就會增加
>>> a = 'ghost' >>> b = 'hello, can you help me install ghost windows xp system' >>> b_set = set( b ) >>> b_set.update( list( a ) ) >>> print len( b_set ) == len( set( b ) ) True >>> a = 'abcostg' >>> b_set.update( list( a ) ) >>> print len( b_set ) == len( set( b ) ) False >>>
2,如果是多個字元呢?
#!/usr/bin/python #coding:utf-8 #str_list = [ 'abc', 'ghost', 'hello' ] str_list = [ 'abc', 'ghost', 'hellox' ] target_str = "abcdefghijklopqrst" target_str_set = set( target_str ) for val in str_list: target_str_set.update( val ) print len( target_str_set ) == len( set( target_str ) )
3,統計出現次數最多的字元
ghostwu@ghostwu:~/python/tmp$ python str3.py [('f', 7), ('s', 5), ('a', 4), ('j', 4), ('k', 3), ('h', 2), ('3', 2), ('1', 2), ('2', 2), ('d', 1), ('l', 1), ('4', 1), (';', 1)] ghostwu@ghostwu:~/python/tmp$ cat str3.py #!/usr/bin/python #coding:utf-8 str = 'askfjkjasf1234fasdfasfsh;lkjfhjf123' l = ( [ ( key, str.count( key ) ) for key in set( str ) ] ) l.sort( key = lambda item : item[1], reverse = True ) print l ghostwu@ghostwu:~/python/tmp$
這裡有個lambda表達式, key指定按哪個鍵排序, item是形參,代表當前的元組,item[1],那就是取元組中第2項,這裡就是字元串的次數,reverse = True,從高到低排序 .
4,統計this模塊中, be, is, than,三個單詞的出現次數
ghostwu@ghostwu:~/python/tmp$ !p python statics.py [('be', 3), ('is', 10), ('than', 8)] ghostwu@ghostwu:~/python/tmp$ cat statics.py #!/usr/bin/python #coding:utf-8 import os this_str = os.popen( "python -m this" ).read() this_str = this_str.replace( '\n', '' ) l = this_str.split( ' ' ) print [ ( x, l.count( x ) ) for x in ['be', 'is', 'than' ] ] ghostwu@ghostwu:~/python/tmp$
os.popen( "python -m this" ).read 讀出命令行python -m this 模塊的執行結果到一個字元串中
5,用位移運算符,換算b, kb, mb之間的轉換關係
ghostwu@ghostwu:~/software$ ls -l sogoupinyin_2.2.0.0102_amd64.deb -rw-rw-r-- 1 ghostwu ghostwu 22852956 2月 2 14:36 sogoupinyin_2.2.0.0102_amd64.deb ghostwu@ghostwu:~/software$ ls -lh sogoupinyin_2.2.0.0102_amd64.deb -rw-rw-r-- 1 ghostwu ghostwu 22M 2月 2 14:36 sogoupinyin_2.2.0.0102_amd64.deb ghostwu@ghostwu:~/software$ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> size = 22852956 >>> print "%s kb" % ( size >> 10 ) 22317 kb >>> print "%s MB" % ( size >> 20 ) 21 MB >>>
6,把列表中的值,連接成字元串
>>> a = [10, 20, 30, 1, 2, 3] >>> s = str( a ) >>> s '[10, 20, 30, 1, 2, 3]' >>> type( s ) <type 'str'> >>> s[1:-1] '10, 20, 30, 1, 2, 3' >>> s.replace( ', ', '', s[1:-1] ) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: an integer is required >>> s[1:-1].replace( ', ', '' ) '102030123' >>>