当前位置: 首页 > news >正文

提高编程思维的python代码

1.通过函数取差。举例:返回有差别的列表元素

from math import floordef difference_by(a,b,fn):b = set(map(fn, b))return [i for i in a if fn(i) not in b]
print(difference_by([2.1, 1.2], [2.3, 3.4], floor))

2.一行代码调用多个函数

def add(a, b):return a + b
def subtract(a ,b):return  a - b
a, b = 4, 5
print((subtract if a>b else add)(a, b))

3.检查列表是否有重复项:有重复项就返回True,无重复项就返回

def has_duplicate(lst):return len(lst) != len(set(lst))
x = ['公共开发', '实验室', 'python']
y = ['公共开发', '实验室', 'python', 'python']

4.合并两个字典

def merge_dictionaries(a, b):return {**a, **b}
a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(merge_dictionaries(a, b))

5.将两个列表转化为字典

def to_dictionary(keys, values):return dict(zip(keys, values))
keys = ['a', 'b', 'c']
values = [2 , 3, 4]
print(to_dictionary(keys, values))

6.使用枚举

lst = ['a', 'b', 'c', 'd']
for index,value in enumerate(lst):print('value', value, 'index', index)

7.执行某代码所花费的时间

import time
start_time = time.time()
a = 2023
b = 2022
c = a - b
print(c)
end_time = time.time()
total_time = end_time - start_time
print('Time:', total_time)

8.Try else

try:print(int('你'))
except:print('有异常发生,请检查:int没法直接强制转换字符"你"')
else:print('try成功才会执行此处')

9.列表出现的频率最多元素

def most_frequent(lst2):return max(lst2, key=lst2.count)
lst1 = ['Python', 'Python', '公共开发', '公共开发', '公共开发', '12345678']
print(most_frequent(lst1)) # 公共开发

10.筛选出最长的字符串

def most_max_length(lst2):return max(lst2, key=len)
lst1 = ['Python', 'Python', '公共开发', '公共开发', '公共开发', '12345678']
print(most_max_length(lst1)) # 公共开发

11.快速修改列表字符元素为整形

def change_int(lst):lst2 = list(map(str, lst))return lst2
lst = [1,2,3,4,5,6]
print(change_int(lst)) # ['1', '2', '3', '4', '5', '6']

12.回文序列检测:所谓回文序列指的是字符串与反向字符串是否相等。

from re import sub
def palindrome(string):s = sub('[\W_]', '', string.lower()) # 中括号内\W_表示用于匹配\W或者_print(s)return s == s[::-1]
print(palindrome('ta  co cat'))

13.字典默认值:通过 Key 取对应的 Value 值,可以通过以下方式设置默认值。如果 get() 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None。

d = {'a': 1, 'b': 2}
print(d.get('c', 3))
http://www.lryc.cn/news/31785.html

相关文章:

  • CSS背景background属性整理
  • AQS底层源码深度剖析-Lock锁
  • 网络编程(二)
  • 访问学者进入美国哪些东西不能带?
  • 灵巧手抓持<分类><仿真>
  • CENTO OS上的网络安全工具(十九)ClickHouse集群部署
  • tesseract -图像识别
  • JavaScript Math 算数对象
  • 一体机HDATA节点添加和删除
  • 关于 interface{} 会有啥注意事项?上
  • Matlab中旧版modem.qammod与新版不兼容
  • 通达信指标公式颜色代码的四种写法(COLOR/RGB)
  • 小程序面试题收集(持续更新中...)
  • 最深情的告白——郁金香(Python实现)
  • 代码随想录算法训练营第六天|242.有效的字母异位词 、349. 两个数组的交集 、 202. 快乐数、1. 两数之和
  • 【STL】模拟实现list
  • Spring Cloud Alibaba全家桶(五)——微服务组件Nacos配置中心
  • 【微信小程序】-- 页面事件 - 下拉刷新(二十五)
  • springboot启动过程加载数据笔记(springboot3)
  • 中文代码86
  • 网络参考模型
  • Spark Tungsten
  • 2023年总结的web前端学习路线分享(学习导读)
  • MyBatis学习笔记(十) —— 动态SQL
  • 剑指 Offer 55 - II. 平衡二叉树
  • 一文吃透前端低代码的 “神仙生活”
  • 【深度学习】预训练语言模型-BERT
  • C++类的组合
  • 2.伪随机数生成器(ctr_drbg)的配置与使用
  • CentOS7 切换图形模式和多用户命令行模式