Python编程小技巧

1. 逻辑判断的几种写法

a, b = 1, 2
if a > b:
    c = a
else:
    c = b
print(c)  # 2

# 三元表达式
c = a if a > b else b
print(c)  # 2

# 列表
c = [b, a][a > b]
print(c)  # 2

# 元组
c = (a > b and a or b)
print(c)  # 2

说明:

# 列表
c = [b, a][a > b]
c = [2, 1][1 > 2]
c = [2, 1][False]
c = [2, 1][0]
>>> False == 0
True
>>> True == 1
True
>>> [2, 1][False]
2
>>> [2, 1][True]
1
# 元组
c = (a > b and a or b)
c = (False and 1 or 2)
c = (False or 2)

2. unicode字符和中文相互转换

# 中文转unicode
a = "你的坚持终将美好"
print(a.encode('unicode-escape').decode())

# unicode字符串转中文
a = "\\u4f60\\u7684\\u575a\\u6301\\u7ec8\\u5c06\\u7f8e\\u597d"
print(a.encode().decode("unicode-escape"))

import ast
print(ast.literal_eval('["\\u4f60\\u7684\\u575a\\u6301\\u7ec8\\u5c06\\u7f8e\\u597d"]'))

3. json.dumps()中文转成unicode的问题

import json
text = "你的坚持,终将美好"
res = json.dumps(text)
print(res)  # "\u4f60\u7684\u575a\u6301\uff0c\u7ec8\u5c06\u7f8e\u597d"
res = json.dumps(text, ensure_ascii=False)
print(res)  # "你的坚持,终将美好"

4. 英文字母往前一位偏移加密小算法

import string

def get_previous_letter(letter_now):
    """
    对字母进行上一位赋值,比如a=z,b=a,c=b,d=b
    """
    letter_previous = ord(letter_now) - 1
    # ord('a')=97
    if letter_previous == 96:
        # ord('z')=122
        letter_previous = 122
    # ord('A')=98
    if letter_previous == 64:
        # ord('Z')
        letter_previous = 90
    # 往后一位赋值,上面的代码需要+1
    # if letter_previous == 123:
    #     letter_previous = 97
    # if letter_previous == 91:
    #     letter_previous = 65
    return chr(letter_previous)


def handle_str(data_str):
    temp_str = ""
    for str_ in str(data_str):
        if str_.lower() in string.ascii_letters:
            letter_previous = get_previous_letter(str_)
            temp_str += letter_previous
        else:
            temp_str += str_
    return temp_str

data = "ifmmp xpsme"
print(handle_str(data))

5. 字段取值

a = {'name':1, 'action':2}
print('%(name)s %(action)s to ' % a)

6. 单例

class Singleton(object):
    __instance = None
    __init_flag = True

    def __init__(self):
        if Singleton.__init_flag:
            Singleton.__init_flag = False
            print('__init__...')
    def __new__(cls, *args, **kwargs):
        if Singleton.__instance is None:
            Singleton.__instance = object.__new__(cls, *args, **kwargs)
        return Singleton.__instance


one = Singleton()
two = Singleton()

7.字典和列表排序

intervals = [[1,3],[2,6],[8,10],[15,18]]
intervals.sort(key=lambda x:x[0])
print(intervals)

dict1={'a':2,'e':3,'f':8,'d':4, 'b':3}
dict2 = sorted(dict1.items(),key=lambda x:(x[1],x[0]))
print(dict2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大帅不是我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值