python 小技巧

1.獲取列表中出現(xiàn)頻率最多的值

a = [1, 2, 3, 1, 2, 3, 3, 3, 3, 2, 1, 5, 4]
 
print (max(set(a), key=a.count))
# 3
 
 
from collections import Counter
 
cnt = Counter(a)
print cnt.most_common(1)
# (3,5)
  1. 判斷翻轉(zhuǎn)字符串是否相等
str1 = '12345'
str2 = '54321'
 
from collections import Counter
 
print (Counter(str1) == Counter(str2))
# True
  1. 翻轉(zhuǎn)字符串或數(shù)字、列表
a = 'abcdefghigklmnopqrstuvwxyz'
print (a[::-1])
# zyxwvutsrqponmlkgihgfedcba
 
print ''.join(list(reversed(a)))
# zyxwvutsrqponmlkgihgfedcba
 
num =123456789
print (int(str(num)[::-1]))
# 987654321
 
a=[1,2,3,4,5]
print(a[::-1])
# [5,4,3,2,1]
  1. 字典排序
d = {'a': '1', 'b': '2', 'c': '3', 'd': '4'}
print (sorted(d.items(), key=lambda x: x[1]))
#[(u'a', u'1'), (u'b', u'2'), (u'c', u'3'), (u'd', u'4')]
 
from operator import itemgetter
print (sorted(d.items(), key=itemgetter(1)))
# [(u'a', u'1'), (u'b', u'2'), (u'c', u'3'), (u'd', u'4')]
 
print (sorted(d, key=d.get))
# [u'a', u'b', u'c', u'd']
  1. 獲取列表中最大值/最小值的索引值
li = [100, 200, 500, 30, 800, 10]
 
 
def minIndex(li):
    return min(range(len(li)), key=li.__getitem__)
 
 
def maxIndex(li):
    return max(range(len(li)), key=li.__getitem__)
 
print minIndex(li)
# 5
 
print maxIndex(li)
# 4

http://www.chenxm.cc/post/656.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 準(zhǔn)備記錄下平時(shí)使用python可以使用的小技巧,主要來自python cookbook里,可以讓代碼更加優(yōu)雅一些,...
    fsc2016閱讀 257評論 1 0
  • 能調(diào)用方法的一定是對象。 技巧#1 字符串翻轉(zhuǎn) 技巧#2 矩陣轉(zhuǎn)置 矩陣轉(zhuǎn)置 自己喜歡的一種寫法: 技巧#3 a ...
    孟軻666閱讀 373評論 1 2
  • 起因 更多Python學(xué)習(xí)技巧:http://xuexi.jikexueyuan.com/course/3.htm...
    極客學(xué)院Wiki閱讀 4,322評論 2 2
  • 在 Python 中字典對象是很重要的概念,因?yàn)?Python 程序運(yùn)行中的各種變量名與變量值都統(tǒng)一存儲于字典中進(jìn)...
    葉俊賢閱讀 6,158評論 0 1
  • 01 同樣是女孩,出身農(nóng)村,有的女孩成為全國摔跤冠軍,從此衣食無憂,受人尊敬,而有的女孩卻在來第一次月經(jīng)后就被父母...
    林洢閱讀 363評論 0 1

友情鏈接更多精彩內(nèi)容