码迷,mamicode.com
首页 > 编程语言 > 详细

python--将书读薄

时间:2019-03-05 18:42:09      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:erro   item   port   变形   不可变   dom   else   file   很多   

python 小技巧

# 小数
import decimal
from decimal import Decimal
Decimal("0.01") + Decimal("0.02")
decimal.getcontext().prec = 4

# 分数
from fractions import Fraction
x = Fraction(4,6)
x = Fraction("0.25")
x


# 检测字符串是否为 数字
x = '569789'

x.isdigit()

#测试所占位数
a = 1234
a.bit_length()

# 字符串的不可变形 = immutability
Str1 = 'Yuxl'
print(Str1)
try:
    Str1[0] = 'XX'
except:
    print("不可更改")
不可更改

>>> import random
>>> def g_rand_range(max):
...     for i in range(1,max+1,1):
...         yield random.randint(1,10)
...
>>> for i in g_rand_range(10):
...     print(i)

#查找列表中某个元素的下标?

In[26]: ['a','b','c'].index('b')
    
# for-else 按照 PEP 8 规范尽量少用
for n in range(2, 100):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n / x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')



# 展平 嵌套 list 等

import itertools

# 简洁,然并卵
l_2 = ([1,2],[3,4],[5,6])
# list(itertools.chain(*l_2))
# list(itertools.chain.from_iterable(l_2))

# 局限性 明显 ,多层就要写很多次
# [l_3 for l in l_2 for l_3 in l]

# 吾之所爱
def flattern(list_nested):
    if not isinstance(list_nested,(list,tuple)):
        raise TypeError('不是 list 或者 tuple 类型!')
    else:
        for l in list_nested:
            if isinstance(l,list):
                tmp = flattern(l)
                for item in tmp:
                    yield item
            else:
                yield l
                
print(list(flattern(l_2)))


# 字典排序
>>> dict_1 = {'a':3,'b':1,'c':2}
>>> sorted(dict_1.items(),key=lambda x:x[1])
[('b', 1), ('c', 2), ('a', 3)]

>>> import operator
>>> file_dict={"a":1,"b":2,"c":3}
>>> sorted(file_dict.items(),key = operator.itemgetter(1),reverse=True)
[('c', 3), ('b', 2), ('a', 1)]

python--将书读薄

标签:erro   item   port   变形   不可变   dom   else   file   很多   

原文地址:https://www.cnblogs.com/Frank99/p/10478595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!