优雅编写Python3 的62个小贴士!

Python基础入门:从变量到异常处理(Task02-1列表)——天池 1.列表 x = [0 for i in range(5)] print(x, type(x)) [0, 0, 0, 0, 0] <class ‘list’> x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0] print(x, type(x)) [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99] <class ‘list’> 1.1 阅读详情

640?wx_fmt=png

今天公众号为大家带来一篇有关Python技巧的文章,可以帮助你编写优雅的Python3代码!


iterable技巧

▍1、创建一个数字序列(从0到10,间隔为2)



 
>>> range(0,10,2)[0, 2, 4, 6, 8]0,10,2)
[0, 2, 4, 6, 8]


▍2、对一串数字求和(从0到10,间隔为2)



 
>>> l = range(0,10,2)>>> sum(l)200,10,2)
>>> sum(l)
20


▍3、检查序列中的任一元素是否为True



 
>>> any(a % 2 for a in range(0,10,2))True2 for a in range(0,10,2))
True


▍4、检查序列中的所有元素是否为True



 
>>> all(a % 2 for a in range(0,10,2))True2 for a in range(0,10,2))
True


▍5、累计求和一串数字序列



 
>>> import numpy as np>>> res = list(np.cumsum(range(0,10,2)))>>> res[ 0, 2, 6, 12, 20]import numpy as np
>>> res = list(np.cumsum(range(0,10,2)))
>>> res
[ 0, 2, 6, 12, 20]


▍6、给定每个iterable,通过添加索引来构造一个元组



 
>>> a = ['Hello', 'world', '!']>>> list(enumerate(a))[(0, 'Hello'), (1, 'world'), (2, '!')]'Hello', 'world', '!']
>>> list(enumerate(a))
[(0, 'Hello'), (1, 'world'), (2, '!')]


▍7、将iterable连接到单个字符串



 
>>> a = ["python","really", "rocks"]>>> " ".join(a)'python really rocks'"python","really", "rocks"]
>>> " ".join(a)
'python really rocks'


▍8、组合两个可迭代的元组或pivot嵌套的iterables



 
# Combining two iterables>>> a = [1, 2, 3]>>> b = ['a', 'b', 'c']>>> z = zip(a, b)>>> z[(1, 'a'), (2, 'b'), (3, 'c')]# Pivoting list of tuples>>> zip(*z)[(1, 2, 3), ('a', 'b', 'c')]
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]

# Pivoting list of tuples
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]


▍9、从iterables中获取最小值/最大值(具有/不具有特定功能)



 
# Getting maximum from iterable>>> a = [1, 2, -3]>>> max(a)2# Getting maximum from iterable>>> min(a)1# Bot min/max has key value to allow to get maximum by appliing function>>> max(a,key=abs)3
>>> a = [1, 2, -3]
>>> max(a)
2

# Getting maximum from iterable
>>> min(a)
1

# Bot min/max has key value to allow to get maximum by appliing function
>>> max(a,key=abs)
3


▍10、可迭代排序(可以通过“compare”函数排序)



 
>>> a = [1, 2, -3]>>> sorted(a)[-3, 1, 2]>>> sorted(a,key=abs)[1, 2, -3]1, 2, -3]
>>> sorted(a)
[-3, 1, 2]

>>> sorted(a,key=abs)
[1, 2, -3]


▍11、将单个字符串拆分为列表



 
>>> s = "a,b,c">>> s.split(",")["a", "b", "c"]"a,b,c"
>>> s.split(",")
["a", "b", "c"]


▍12、初始化一个包含重复数字的列表



 
>> [1]* 10[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]10
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]


▍13、合并/插入两个字典



 
>>> a = {"a":1, "b":1}>>> b = {"b":2, "c":1}>>> a.update(b)>>> a{"a":1, "b":2, "c":1}"a":1, "b":1}
>>> b = {"b":2, "c":1}
>>> a.update(b)
>>> a
{"a":1, "b":2, "c":1}


▍14、命名和保存iterables切片



 
# Naming slices (slice(start, end, step))>>> a = [0, 1, 2, 3, 4, 5]>>> LASTTHREE = slice(-3, None)>>> LASTTHREEslice(-3, None, None)>>> a[LASTTHREE][3, 4, 5]
>>> a = [0, 1, 2, 3, 4, 5]
>>> LASTTHREE = slice(-3, None)
>>> LASTTHREE
slice(-3, None, None)
>>> a[LASTTHREE]
[3, 4, 5]


▍15、在列表中查找项的索引



 
>>> a = ["foo", "bar", "baz"]>>> a.index("bar")1"foo", "bar", "baz"]
>>> a.index("bar")
1


▍16、在iterables中查找最小/最大项的索引



 
>>> a = [2, 3, 1]>>> min(enumerate(a),key=lambda x: x[1])[0]22, 3, 1]
>>> min(enumerate(a),key=lambda x: x[1])[0]
2


▍17、旋转iterables的k个元素



 
>>> a = [1, 2, 3, 4]>>> k = 2>>> a[-2:] + a[:-2][3, 4, 1, 2]1, 2, 3, 4]
>>> k = 2
>>> a[-2:] + a[:-2]
[3, 4, 1, 2]


▍18、删除字符串末尾/开始/两端无用的字符



 
>>> name = "//George//">>> name.strip("/")'George'>>> name.rstrip("/")'//George'>>> name.lstrip("/")'George//'"//George//"
>>> name.strip("/")
'George'
>>> name.rstrip("/")
'//George'
>>> name.lstrip("/")
'George//'


▍19、倒序iterables的顺序(字符串、列表等)



 
# Reversing string>>> s = "abc">>> s[::-1]"cba"# Reversing list>>> l = ["a", "b", "c"]>>> l[::-1]["c", "b", "a"]
>>> s = "abc"
>>> s[::-1]
"cba"

# Reversing list
>>> l = ["a", "b", "c"]
>>> l[::-1]
["c", "b", "a"]


branching技巧

▍20、多个short-cut



 
>>> n = 10>>> 1 < n < 20True10
>>> 1 < n < 20
True


▍21、For-else结构在搜索某些东西并找到它时很有用



 
for i in mylist:     if i == theflag:         break     process(i)else:     raise ValueError("List argument missing terminal flag.")in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")


▍22、Trenary operator



 
>>> "Python ROCK" if True else " I AM GRUMPY""Python ROCK""Python ROCK" if True else " I AM GRUMPY"
"Python ROCK"


▍23、Try-catch-else结构



 
try:     foo()except Exception:     print("Exception occured")else:     print("Exception didnt occur")finally:     print("Always gets here")
    foo()
except Exception:
    print("Exception occured")
else:
    print("Exception didnt occur")
finally:
    print("Always gets here")


▍24、While-else结构



 
i = 5while i > 1:     print("Whil-ing away!")     i -= 1     if i == 3:         breakelse:    print("Finished up!")

while i > 1:
    print("Whil-ing away!")
    i -= 1
    if i == 3:
        break
else:
    print("Finished up!")


comprehensions(推导式)技巧

▍25、List推导式



 
>>> m = [x ** 2 for x in range(5)]>>> m[0, 1, 4, 9, 16]2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]


▍26、Set推导式



 
>>> m = {x ** 2 for x in range(5)}>>> m{0, 1, 4, 9, 16}2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}


▍27、Dict推导式



 
>>> m = {x: x ** 2 for x in range(5)}>>> m{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


▍28、Generator推导式



 
# A generator comprehension is the lazy version of a list comprehension.>>> m = (x ** 2 for x in range(5))>>> m<generator object <genexpr> at 0x108efe408>>>> list(m)[0, 1, 4, 9, 16]>>> m = (x ** 2 for x in range(5))>>> next(m)0>>> list(m)[1, 4, 9, 16]
>>> m = (x ** 2 for x in range(5))
>>> m
<generator object <genexpr> at 0x108efe408>
>>> list(m)
[0, 1, 4, 9, 16]

>>> m = (x ** 2 for x in range(5))
>>> next(m)
0
>>> list(m)
[1, 4, 9, 16]


▍29、list推导使用当前值和过往值



 
>>> a = [1, 2, 4,2]>>> [y - x for x,y in zip(a,a[1:])][1, 2, -2]1, 2, 4,2]
>>> [y - x for x,y in zip(a,a[1:])]
[1, 2, -2]


unpacking技巧

▍30、从iterable解压缩变量



 
# One can unpack all iterables (tuples, list etc)>>> a, b, c = 1, 2, 3>>> a, b, c(1, 2, 3)>>> a, b, c = [1, 2, 3]>>> a, b, c(1, 2, 3)
>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)

>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)


▍31、交换变量值



 
>>> a, b = 1, 2>>> a, b = b, a>>> a, b(2, 1)1, 2
>>> a, b = b, a
>>> a, b
(2, 1)


▍32、在不指示所有元素的情况下从iterable解包变量



 
>>> a, *b, c = [1, 2, 3, 4, 5]>>> a1>>> b[2, 3, 4]>>> c51, 2, 3, 4, 5]
>>> a
1
>>> b
[2, 3, 4]
>>> c
5


▍33、使用splat运算符解包变量



 
>>> def test(x, y, z):>>>      print(x, y, z)>>> res = test(*[10, 20, 30])10 20 30>>> res = test(**{'x': 1, 'y': 2, 'z': 3} )10 20 30 view rawdef test(x, y, z):
>>>      print(x, y, z)
>>> res = test(*[10, 20, 30])
10 20 30
>>> res = test(**{'x': 1, 'y': 2, 'z': 3} )
10 20 30
view raw


Itertools技巧

▍34、Flatten iterables



 
>>> a = [[1, 2], [3, 4], [5, 6]]>>> list(itertools.chain.from_iterable(a))[1, 2, 3, 4, 5, 6]1, 2], [3, 4], [5, 6]]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]


▍35、从iterables创建笛卡尔积



 
>>> for p in itertools.product([1, 2, 3], [4, 5]):>>>      print(''.join(str(x) for x in p))(1, 4)(1, 5)(2, 4)(2, 5)(3, 4)(3, 5)for p in itertools.product([1, 2, 3], [4, 5]):
>>>      print(''.join(str(x) for x in p))

(1, 4)
(1, 5)
(2, 4)
(2, 5)
(3, 4)
(3, 5)


▍36、从iterable创建排列



 
>>> for p in itertools.permutations([1, 2, 3, 4]):>>>      print(''.join(str(x) for x in p))123132213231312321for p in itertools.permutations([1, 2, 3, 4]):
>>>      print(''.join(str(x) for x in p))
123
132
213
231
312
321


▍37、从iterable创建ngram



 
>>> from itertools import islice>>> def n_grams(a, n):...          z = (islice(a, i, None) for i in range(n))...          return zip(*z)...>>> a = [1, 2, 3, 4, 5, 6]>>> n_grams(a, 3)[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]>>> n_grams(a, 2)[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]>>> n_grams(a, 4)[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]from itertools import islice
>>> def n_grams(a, n):
...          z = (islice(a, i, None) for i in range(n))
...          return zip(*z)
...
>>> a = [1, 2, 3, 4, 5, 6]
>>> n_grams(a, 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> n_grams(a, 2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> n_grams(a, 4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]


▍38、使用填充组合元组的两个迭代器或使用填充pivot嵌套迭代



 
>>> import itertools as it>>> x = [1, 2, 3, 4, 5]>>> y = ['a', 'b', 'c']>>> list(zip(x, y))[(1, 'a'), (2, 'b'), (3, 'c')]>>> list(it.zip_longest(x, y))[(1, 'a'), (2, 'b'), (3, 'c'), (4, None), (5, None)]import itertools as it
>>> x = [1, 2, 3, 4, 5]
>>> y = ['a', 'b', 'c']
>>> list(zip(x, y))
[(1, 'a'), (2, 'b'), (3, 'c')]

>>> list(it.zip_longest(x, y))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, None), (5, None)]


▍39、从一个iterable n中创建k个组合



 
>>> import itertools>>> bills = [20, 20, 20, 10, 10, 10, 10, 10, 5, 5, 1, 1, 1, 1, 1]>>> list(itertools.combinations(bills, 3))[(20, 20, 20), (20, 20, 10), (20, 20, 10), ... ]import itertools
>>> bills = [20, 20, 20, 10, 10, 10, 10, 10, 5, 5, 1, 1, 1, 1, 1]
>>> list(itertools.combinations(bills, 3))
[(20, 20, 20), (20, 20, 10), (20, 20, 10), ... ]


▍40、在给定函数情况下创建一个迭代的累积结果



 
>>> import itertools>>> list(itertools.accumulate([9, 21, 17, 5, 11, 12, 2, 6], min))[9, 9, 9, 5, 5, 5, 2, 2]import itertools
>>> list(itertools.accumulate([9, 21, 17, 5, 11, 12, 2, 6], min))
[9, 9, 9, 5, 5, 5, 2, 2]


▍41、创建一个迭代器,只要谓词为True,就从iterable返回元素



 
>>> import itertools>>> itertools.takewhile(lambda x: x < 3, [0, 1, 2, 3, 4])[0, 1, 2]>>> it.dropwhile(lambda x: x < 3, [0, 1, 2, 3, 4])[3, 4]import itertools
>>> itertools.takewhile(lambda x: x < 3, [0, 1, 2, 3, 4])
[0, 1, 2]

>>> it.dropwhile(lambda x: x < 3, [0, 1, 2, 3, 4])
[3, 4]


▍42、创建一个迭代器,它从iterable中过滤元素,只返回谓词为False的元素



 
>>> import itertools# keeping only false values>>> list(itertools.filterfalse(bool, [None, False, 1, 0, 10]))[None, False, 0]import itertools
# keeping only false values
>>> list(itertools.filterfalse(bool, [None, False, 1, 0, 10]))
[None, False, 0]


▍43、创建一个迭代器,使用从迭代的迭代中获得的参数来计算函数



 
>>> import itertools>>> import operator>>> a = [(2, 6), (8, 4), (7, 3)]>>> list(itertools.starmap(operator.mul, a))[12, 32, 21]import itertools
>>> import operator
>>> a = [(2, 6), (8, 4), (7, 3)]
>>> list(itertools.starmap(operator.mul, a))
[12, 32, 21]


collections技巧

▍44、设置基本操作



 
>>> A = {1, 2, 3, 3}>>> Aset([1, 2, 3])>>> B = {3, 4, 5, 6, 7}>>> Bset([3, 4, 5, 6, 7])>>> A | Bset([1, 2, 3, 4, 5, 6, 7])>>> A & Bset([3])>>> A - Bset([1, 2])>>> B - Aset([4, 5, 6, 7])>>> A ^ Bset([1, 2, 4, 5, 6, 7])>>> (A ^ B) == ((A - B) | (B - A))True1, 2, 3, 3}
>>> A
set([1, 2, 3])
>>> B = {3, 4, 5, 6, 7}
>>> B
set([3, 4, 5, 6, 7])
>>> A | B
set([1, 2, 3, 4, 5, 6, 7])
>>> A & B
set([3])
>>> A - B
set([1, 2])
>>> B - A
set([4, 5, 6, 7])
>>> A ^ B
set([1, 2, 4, 5, 6, 7])
>>> (A ^ B) == ((A - B) | (B - A))
True


▍45、计数器数据结构(无序集合,其中元素存储为字典键,其计数存储为字典值)



 
import collections>>> A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])>>> ACounter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})>>> A.most_common(1)[(3, 4)]>>> A.most_common(3)[(3, 4), (1, 2), (2, 2)]

>>> A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])
>>> A
Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})
>>> A.most_common(1)
[(3, 4)]
>>> A.most_common(3)
[(3, 4), (1, 2), (2, 2)]


▍46、默认字典结构(字典的子类,在访问不存在的键时检索默认值)



 
>>> import collections>>> m = collections.defaultdict(int)>>> m['a']0>>> m = collections.defaultdict(str)>>> m['a']''>>> m['b'] += 'a'>>> m['b']'a'>>> m = collections.defaultdict(lambda: '[default value]')>>> m['a']'[default value]'>>> m['b']'[default value]'>>> m = collections.defaultdict(list)>>> m['a'][]import collections
>>> m = collections.defaultdict(int)
>>> m['a']
0

>>> m = collections.defaultdict(str)
>>> m['a']
''
>>> m['b'] += 'a'
>>> m['b']
'a'

>>> m = collections.defaultdict(lambda: '[default value]')
>>> m['a']
'[default value]'
>>> m['b']
'[default value]'

>>> m = collections.defaultdict(list)
>>> m['a']
[]


▍47、有序的dict结构(保持有序字典的子类)



 
>>> from collections import OrderedDict>>> d = OrderedDict.fromkeys('abcde')>>> d.move_to_end('b')>>> ''.join(d.keys())'acdeb'>>> d.move_to_end('b', last=False)>>> ''.join(d.keys())'bacde'from collections import OrderedDict

>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> ''.join(d.keys())
'acdeb'

>>> d.move_to_end('b', last=False)
>>> ''.join(d.keys())
'bacde'


▍48、Deques结构(Deques是堆栈和队列的概括)



 
>>> import collection>>> Q = collections.deque()>>> Q.append(1)>>> Q.appendleft(2)>>> Q.extend([3, 4])>>> Q.extendleft([5, 6])>>> Qdeque([6, 5, 2, 1, 3, 4])>>> Q.pop()4>>> Q.popleft()6>>> Qdeque([5, 2, 1, 3])>>> Q.rotate(3)>>> Qdeque([2, 1, 3, 5])>>> Q.rotate(-3)>>> Qdeque([5, 2, 1, 3])>>> last_three = collections.deque(maxlen=3)>>> for i in range(4):...         last_three.append(i)...         print ', '.join(str(x) for x in last_three)...00, 10, 1, 21, 2, 32, 3, 4import collection
>>> Q = collections.deque()
>>> Q.append(1)
>>> Q.appendleft(2)
>>> Q.extend([3, 4])
>>> Q.extendleft([5, 6])
>>> Q
deque([6, 5, 2, 1, 3, 4])
>>> Q.pop()
4
>>> Q.popleft()
6
>>> Q
deque([5, 2, 1, 3])
>>> Q.rotate(3)
>>> Q
deque([2, 1, 3, 5])
>>> Q.rotate(-3)
>>> Q
deque([5, 2, 1, 3])

>>> last_three = collections.deque(maxlen=3)
>>> for i in range(4):
...         last_three.append(i)
...         print ', '.join(str(x) for x in last_three)
...
0
0, 1
0, 1, 2
1, 2, 3
2, 3, 4


▍49、命名元组结构(创建类元组的对象,这些对象的字段可通过属性查找访问,也可索引和迭代)



 
>>> import collections>>> Point = collections.namedtuple('Point', ['x', 'y'])>>> p = Point(x=1.0, y=2.0)>>> pPoint(x=1.0, y=2.0)>>> p.x1.0>>> p.y2.0import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(x=1.0, y=2.0)
>>> p
Point(x=1.0, y=2.0)
>>> p.x
1.0
>>> p.y
2.0


▍50、使用字典来存储Switch



 
>>> func_dict = {'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y}>>> func_dict['sum'](9,3)12>>> func_dict['subtract'](9,3)6'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y}
>>> func_dict['sum'](9,3)
12
>>> func_dict['subtract'](9,3)
6


▍51、数据类结构



 
>>> from dataclasses import dataclass>>> @dataclass>>> class DataClassCard:>>>      rank: str>>>      suit: str >>> queen_of_hearts = DataClassCard('Q', 'Hearts')>>> queen_of_hearts.rank'Q'>>> queen_of_heartsDataClassCard(rank='Q', suit='Hearts')>>> queen_of_hearts == DataClassCard('Q', 'Hearts')Truefrom dataclasses import dataclass

>>> @dataclass
>>> class DataClassCard:
>>>     rank: str
>>>      suit: str

>>> queen_of_hearts = DataClassCard('Q', 'Hearts')
>>> queen_of_hearts.rank
'Q'
>>> queen_of_hearts
DataClassCard(rank='Q', suit='Hearts')
>>> queen_of_hearts == DataClassCard('Q', 'Hearts')
True


其他技巧

▍52、生成uuid



 
# This creates a randomized#128-bit number that will almost certainly be unique.# In fact, there are over 2¹²² possible#UUIDs that can be generated.#That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).>>> import uuid>>> user_id = uuid.uuid4()>>> user_idUUID('7c2faedd-805a-478e-bd6a-7b26210425c7')
#128-bit number that will almost certainly be unique.
# In fact, there are over 2¹²² possible
#UUIDs that can be generated.
#That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).

>>> import uuid
>>> user_id = uuid.uuid4()
>>> user_id
UUID('7c2faedd-805a-478e-bd6a-7b26210425c7')


▍53、使用LRU缓存进行记忆



 
import functools@functools.lru_cache(maxsize=128)def fibonacci(n):     if n == 0:         return 0     elif n == 1:         return 1     return fibonacci(n - 1) + fibonacci(n - 2)

@functools.lru_cache(maxsize=128)
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)


▍54、Suppression of expressions



 
>>> from contextlib import suppress>>> with contextlib.suppress(ZeroDivisionError):>>>  10/0# No exception raisedfrom contextlib import suppress
>>> with contextlib.suppress(ZeroDivisionError):
>>> 10/0
# No exception raised


▍55、在需要设置和拆卸时创建上下文管理


640?wx_fmt=png

地址:

https://docs.python.org/2/library/contextlib.html?source=post_page---------------------------


▍56、一种处理文件路径的优雅方法(3.4≥)



 
>>> from pathlib import Path>>> data_folder = Path("source_data/text_files/)# Path calculation and metadata>>> file_to_open = data_folder / "raw_data.txt">>> file_to_open.name"raw_data.txt">>> file_to_open.suffix"txt">>>file_to_open.stem"raw_data" # Files functions>>> f = open(file_to_open)>>> f.read()# content of the file>>> file_to_open.exists()Truefrom pathlib import Path
>>> data_folder = Path("source_data/text_files/)

# Path calculation and metadata
>>> file_to_open = data_folder / "
raw_data.txt"
>>> file_to_open.name
"
raw_data.txt"
>>> file_to_open.suffix
"
txt"
>>>file_to_open.stem
"
raw_data"

# Files functions
>>> f = open(file_to_open)
>>> f.read()
# content of the file
>>> file_to_open.exists()
True


▍57、将标准操作符实现为类的函数


640?wx_fmt=png

地址:

https://docs.python.org/3/library/operator.html?source=post_page---------------------------


▍58、创建装饰器来分离concerns



 
>>>from functools import wraps>>>def add_sandwich(wrapped):>>>      @wraps(wrapped)>>>      def wrapper(*args, **kwargs):>>>            return wrapped(*args, **kwargs) + ' sandwich'>>>      return wrapper>>>@add_sandwich>>>def ham():>>>     return 'ham'>>>ham()'ham sandwich'import wraps

>>>def add_sandwich(wrapped):
>>>      @wraps(wrapped)
>>>      def wrapper(*args, **kwargs):
>>>            return wrapped(*args, **kwargs) + ' sandwich'
>>>      return wrapper

>>>@add_sandwich
>>>def ham():
>>>     return 'ham'

>>>ham()
'ham sandwich'


▍59、使用yield创建一个简单的迭代器



 
>>> def foo(lst):>>>      for x in lst:>>>          yield x>>>          yield x*2>>> a = [1, 3]>>> list(foo(a))[1, 2, 3, 6]def foo(lst):
>>>      for x in lst:
>>>          yield x
>>>          yield x*2

>>> a = [1, 3]
>>> list(foo(a))
[1, 2, 3, 6]


▍60、yield from use cases and tricks


640?wx_fmt=png

地址:

https://stackoverflow.com/questions/9708902/in-practice-what-are-the-main-uses-for-the-new-yield-from-syntax-in-python-3?source=post_page---------------------------


彩蛋

▍61、Anti-gravity



 
import antigravityantigravity.fly()

antigravity.fly()


▍62、The Zen of Python



 
>>> import thisThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren not special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one and preferably only one obvious way to do it.Although that way may not be obvious at first unless you are Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it is a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea let us do more of those!


希望以上62个小贴士对你在今天的学习和工作中有所帮助哦!


另外,廖雪峰老师的价值1980的资料还有100个免费名额,有兴趣的可以去领一波。80%的人都被裁员了,还好我有数据分析硬技能

Windchill许可优化实战:从97%到68%使用率的四步法 并发用户许可(Concurrent User License)是PLM系统中基础且关键的授权模型,其核心原理在于按会话生命周期动态分配与回收资源,而非静态绑定用户。该模型的技术价值体现在可伸缩性、成本可控性和多角色隔离能力,广泛应用于Windchill、Teamcenter等主流PLM平台。然而在制造业真实场景中,许可常因会话滞留、模块级消耗不均、心跳保活冗余等行为导致高占用低效用——即‘许可黑洞’现象。本文聚焦Windchill许可体系的三层耦合结构(FlexNet服务层、Windchill应用层、用户行 阅读详情

相关推荐

python语句十大优雅写法

我们都知道,Python 的设计哲学是「优雅」、「明确」、「简单」。这也许很多人选择 Python 的原因。但是我收到有些伙伴反馈,他写的 Python 并不优雅,甚至很臃肿,那可能是你的姿势不对哦!今天就给大家带来 Python 语句的十大优雅之法。

新手学习Python需要知道的100个小技巧,加班一晚上终于整理出来了!

新手学习Python需要知道的100个小技巧,加班一晚上终于整理出来了!

分享Python知识 664

AD9361 SDR接收机FPGA实现与寄存器配置实战指南

软件定义无线电(SDR)通过可配置的硬件平台取代传统固定功能电路,实现多频段、多协议的灵活无线通信。其核心原理在于将射频前端数字化,并依靠软件定义信号处理流程。AD9361作为集成度极高的射频收发器,内部融合了混频器、滤波器、ADC等模块,支持70MHz至6GHz的频段覆盖,通过SPI寄存器配置即可改变工作参数,大幅降低硬件设计复杂度。在实际工程中,FPGA承担着数据桥接与高速数字接口处理的关键职责,尤其需要掌握LVDS数据的DDR采样、位对齐与帧同步技术。结合一个实际接收机项目,文章详细梳理了AD9361

weixin_33895475的博客 484

Python 小贴士(1)pythonic 思维

编写高质量 Python 代码的方法 笔记

yspg_217的博客 739

matlab特征提取和分类_SAST Weekly|MATLAB机器学习初探——做个心音分类器

SAST weekly 是由电子工程系学生科协推出的科技系列推送,内容涵盖信息领域技术科普、研究前沿热点介绍、科技新闻跟进探索等多个方面,帮助同学们增长姿势,开拓眼界,每周更新,欢迎关注!欢迎愿意分享知识的同学投稿至 eesast@mail.tsinghua.edu.cn , 期待你的作品!本期的SAST weekly,想跟大家分享一下如何用MATLAB进行初步的机器学习,构建一个正常/...

weixin_36453829的博客 5585

图解“交易·支付·清结算·账务”全局

这个过程大致是这样的,用户先到平台选择喜欢的“餐品”,然后“下单”,生成交易“账单”,用户选择支付方式进行“支付”,支付成功后平台要履行承诺把餐送到,“履约”完成以后平台就开始进行各方利益的“清分”,计算清楚应给谁多少钱,并“记账”,最后将款项“结算”给商家,这个过程如图7所示。交易系统请求订单系统创建订单,因为不清楚平台和商家之间的清结算协议,所以暂且认为所有优惠由平台提供给用户,后续平台再基于协议跟商家之间做优惠的分摊,将上述商品、优惠、计价等信息集成到一起,就得到了完成的订单信息了,如表4所示。

wjianwei666的专栏 1万+

30个Python的最佳实践小技巧

完整的文档,请点击这里(https://pillow.readthedocs.io/en/stable/)。另外,在 IPython shell 中,你还可以通过 Out[n] 获取表达式 In[n] 的值。完整的命令列表,请点击此处查看(https://ipython.readthedocs.io/en/stable/interactive/magics.html)。这项变更背后的动机,请参阅 PEP-0238(https://www.python.org/dev/peps/pep-0238/)。

WANGWUSAN66的博客 1381

lenovo联想拯救者Legion Y9000P 2022款2023款2024款笔记本电脑(82RF,82WK,82WQ,83DE,83DF)原装出厂Windows11预装OEM系统镜像下载

联想原装出厂系统自带所有驱动、出厂主题壁纸、系统属性联机支持标志、系统属性专属LOGO标志、Office办公软件、联想电脑管家、联想浏览器、联想软件商店、legionzone控制中心等预装程序。链接:https://pan.baidu.com/s/1YBji_oh7xOkq-NxnS8Mm8g?链接:https://pan.baidu.com/s/1S7_enXmuoja1a9ASvUT5Fg?拯救者Legion Y9000P IRX9H 2024款【83DE】原厂Win11系统包。

QQ17855069的博客 6571

python编程小知识_9个Python编程小贴士

分享一篇文章,没有什么奇技淫巧,只是一些简单的小贴士,贴到这里用来提醒一下自己:Python编程方面的一些技巧。1. list切片的技巧 somelist[start:end:stride]test = [1, 2, 3, 4, 5]# 从索引最开始到结束,每隔两个取出一个# 实际上就是肉眼数的奇数位,索引的偶数位odds = test[::2]print(odds) # 结果 -> [1,...

weixin_39798031的博客 238

【WRFDA教程】客观分析(OBSGRID)详解

客观分析(OBSGRID)详解

WW、forever的博客 1140

YOLO11涨点优化:Loss魔改 | WIoU (Wise-IoU) v3版本全面替换,基于动态非单调聚焦机制,让模型更聪明地学习

YOLOv11目标检测中的WIoU v3损失函数改进 本文探讨了YOLOv11目标检测模型中CIoU损失函数的局限性,并提出了WIoU v3改进方案。关键发现包括: CIoU的缺陷:在低质量样本(小目标/遮挡目标)上过度惩罚,导致模型优化方向偏离,小目标AP往往比大目标低30%左右。 WIoU v3的创新: 动态非单调聚焦机制:根据样本"离群度"智能分配梯度 让模型重点优化中等质量样本,减少对低质量样本的无效关注 采用指数移动平均来自适应调整质量评判标准 实际效果:WIoU v3在保持大

2601_95807009的博客 433

优雅编写Python3的62个小贴士!

来源 |量化投资与机器学习(ID:Lhtz_Jqxx)今天公众号为大家带来一篇有关Python技巧的文章,可以帮助你编写优雅的Python3代码!iterable技巧▍...

Python大本营的博客 255

杰理SDK入门教程(一):SDK的四种编译方式的使用

杰理SDK提供了四种主要编译方式:1) JL Studio官方IDE,适合初学者;2) VS Code轻量级编辑器,需在SDK根目录打开;3) 命令行/脚本编译,灵活支持自动化;4) Code::Blocks开源IDE。每种方式都有详细操作指南,开发者可根据需求选择,初学者推荐从JL Studio开始熟悉编译流程。环境配置注意事项和编译成功标识均有明确说明,确保开发效率。

qq_42014563的博客 1170

python3 写文件多c2_优雅编写Python3的62个小贴士!

原标题:优雅编写Python3的62个小贴士!作者 | QIML编辑部来源 | 量化投资与机器学习(ID:Lhtz_Jqxx)今天公众号为大家带来一篇有关Python技巧的文章,可以帮助你编写优雅的Python3代码!iterable技巧▍1、创建一个数字序列(从0到10,间隔为2)>>>range(0,10,2)[0, 2, 4, 6, 8]▍2、对一串数字求和(从0到10,间...

weixin_39778214的博客 197

【Python爬虫(90)】以Python爬虫为眼,洞察金融科技监管风云

本文聚焦爬虫技术在金融科技监管中的应用。开篇阐述金融科技发展带来监管挑战,引出爬虫技术的重要性。接着介绍金融科技监管政策与合规要求,包括政策法规体系、合规细则及政策变化应对。随后探讨爬虫技术选型、数据监测策略、风险指标抓取及案例实操。还阐述基于爬虫数据构建风险预警与防控机制,含模型构建、阈值设定等。最后总结爬虫技术应用成果,展望其与人工智能融合、适应新监管需求及重视数据安全的未来发展趋势。

邓邓子的博客 1066

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

优雅编写Python3 的62个小贴士

iterable技巧 ▍1、创建一个数字序列(从0到10,间隔为2) >>>range(0,10,2)[0,2,4,6,8] ▍2、对一串数字求和(从0到10,间隔为2) >>>l = range(0,10,2)>>>sum(l)20 ▍3、检查序列中的任一元素是否为True >&g...

weixin_30314793的博客 252

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

告别混乱的直方图!用JoyPy轻松绘制鸢尾花数据集的山脊线图(附完整代码)

本文介绍了如何使用JoyPy工具绘制鸢尾花数据集的山脊线图(Ridgeline Plots),解决传统直方图在多组数据分布比较中的视觉混乱问题。通过详细代码示例和实战技巧,帮助读者轻松实现专业级数据可视化,提升数据分析效率。

weixin_26767391的博客 355

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

GPT-4驱动的Python日冕图仪表盘:一条提示词生成可下钻可视化

日冕图(Sunburst)是一种支持多层级嵌套、面积正比于数值的环形可视化图表,广泛应用于组织架构分析、用户行为路径追踪和系统依赖拓扑展示等场景。其核心原理在于极坐标空间下的层级扇区映射与动态下钻交互,相比饼图具备深度分解能力,相比树图更符合人类对比例关系的视觉感知。技术价值体现在降低业务语义到图表呈现的转换成本,实现自然语言→结构化查询→可视化配置的端到端自动化。典型应用场景包括销售费用分层归因、电商转化漏斗分析、IT服务SLA监控等。本文聚焦GPT-4作为语义编译器,结合Plotly Sunburst与

diaomeijiao3430的博客 533

AI智能棋盘集成PCA9685精准驱动舵机角度转动

本文介绍如何利用PCA9685 PWM芯片实现多路舵机的高精度角度控制,解决树莓派直接驱动时的CPU占用高、信号抖动和扩展性差等问题,适用于AI棋盘、机器人等需要稳定PWM输出的嵌入式场景。

weixin_31800911的博客 579

EEG-Conformer 数据增强秘籍:Segmentation & Reconstruction 如何让分类准确率飙升

**EEG-Conformer 数据增强**一直是脑电解码领域的痛点:样本太少、信噪比太低,Transformer 再强也容易过拟合。本文将深入拆解 EEG-Conformer(卷积 Transformer)官方代码中的 **Segmentation & Reconstruction(S&R)数据增强**方法,用通俗的语言讲清楚它如何把一段 1 秒的脑电信号"一分为八、随机重组",从而让分类准确率

gitblog_00128的博客 220

AI推荐助手:从猜喜好到懂需求的范式革命

推荐系统正经历从统计预测到语义理解的根本性转变。传统协同过滤与深度学习模型受限于意图稀疏性、上下文失焦和决策链断裂,难以应对用户真实场景中的多约束、动态化、长链条任务需求。以大语言模型为认知底座的AI助手,通过结构化意图解析、跨域知识图谱调度与闭环式任务规划,重构了‘推荐’的技术内涵——它不再输出商品链接,而是交付可执行方案。这种演进本质是人机交互范式的升级,核心价值在于降低用户完成目标的行动步数。本文聚焦AI推荐助手的工程落地路径,涵盖RAG+轻量Agent架构设计、高可用知识库构建及四段式对话协议等关键

cqbh2011的博客 420

python 30个技巧、小贴士(1)

1. Python 版本 在此想提醒各位:自2020年1月1日起,Python 官方不再支持 Python 2。本文中的很多示例只能在 Python 3 中运行。如果你仍在使用 Python 2.7,请立即升级。 2. 检查 Python 的最低版本 你可以在代码中检查 Python 的版本,以确保你的用户没有在不兼容的版本中运行脚本。检查方式如下: if not sys.version_info > (2, 7): #. berate your user for running a 10 ye

隔壁小红馆 405

Python 10个优雅的写法,你会吗?

优雅的代码读起来像诗一样美。talk is cheap,show me the code! 1. 一行代码实现2个变量值交换 你能想出一种不用第三个变量就能交换两个变量的方法吗?请看: a = 1 b = 2 a, b = b, a 2. 不用循环实现重复字符串 name = "程序员石磊" print(name * 4) 输出: 程序员石磊程序员石磊程序员石磊程序员石磊 3. 字符转置 sentence = "程序员石磊" reversed = sentence[::-1] print(rev.

程序员石磊 2959

Python3内置函数

Python Standard Library based on Python 3.7.3 https://docs.python.org/3/library/ Python标准库 - 内置函数 Link: https://docs.python.org/3/library/functions.html 说明 print 后的 # 注释为输出和相关说明,包含所有 Python3....

墨1024 371

MIPS指令可以分成以下各类

空操作 no-op;  寄存器/寄存器传输:用得很广,包括条件传输在内;  常数加载:作为数值和地址的整型立即数;    算术/逻辑指令;      整数乘法、除法和求余数;       整数乘加;          加载和存储;        跳转、子程序调用和分支;      断点和自陷;    CP0功能:CPU控制指令  浮点;  用户态的...

weixin_30595035的博客 1883
上一篇: 推荐几个清华和哈工大学霸的公众号,值得学习
下一篇: 微软出Python教程了
菜鸟学Python
博客等级 码龄9年 8171粉丝 571原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址