python 小技巧

2018-08-17  本文已影响0人  和尚我不念经

1.获取列表中出现频率最多的值

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. 判断翻转字符串是否相等
str1 = '12345'
str2 = '54321'
 
from collections import Counter
 
print (Counter(str1) == Counter(str2))
# True
  1. 翻转字符串或数字、列表
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

上一篇下一篇

猜你喜欢

热点阅读