Python 代码片段收藏!

【Qt-4】QT基于qhttp-server搭建http服务器 QT搭建http服务器 阅读详情
import operator
values = [1, 2, 3, 4, 5]
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))
print('min_index:', min_index, 'min_value:', min_value)
print('max_index:', max_index, 'max_value:', max_value)
# Out
min_index: 0 min_value: 1
max_index: 4 max_value: 5

list 中连续元素之间的差

Python资源共享群:626017123

from itertools import islice
ls = [1,2,3,5,8]
diff = [j-i for i,j in zip(ls, islice(ls, 1, None))]
print(diff)
# Out
[1, 1, 2, 3]

删除列表中的重复元素

下面这种方法不能维持顺序:

x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
list(set(x))
# Out
[8, 1, 4, 5]

下面的方法,可以维持顺序:

from collections import OrderedDict
x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
list(OrderedDict.fromkeys(x))
# Out
[1,8,4,5]

并行遍历2个列表

a = [1, 2, 3]
b = [4, 5, 6]
for (a_val, b_val) in zip(a, b):
    print(a_val, b_val)
# Out
1 4
2 5
3 6

合并列表值

输入的两个数组,输出一个是数组&值相加或者相乘:

# input
first = [1,2,3,4,5]
second = [6,7,8,9,10]
#output
three = [7,9,11,13,15]
# The zip function is useful here, used with a list comprehension.
# add
[x + y for x, y in zip(first, second)]
# other
[x*y for x, y in zip(first, second)]
[max(x,y) for x, y in zip(first, second)]

参考:

  • Python中的常用代码

字典处理

字典做交、差、并

a={'name':'michael','age':"27",'sex':'male'}
b={'name':'hqh','age':'27'}
{k:a[k] for k in a.keys()-b.keys()}
out: {'sex': 'male'}
dict(a.items()-b.items())
out: {'name': 'michael', 'sex': 'male'}

需要注意的是,当字典的值有字典时, a.items()-b.items() 这种方式会报错 TypeError: unhashable type: 'dict' ;

参考:

  • cookbook-查找两字典的相同点
  • 简书-Python 字典操作进阶

字典的Key与Value对调

m = {'A': 1, 'B': 2, 'C': 3}
invert_map_key_value = lambda m: dict(zip(m.values(), m.keys()))
invert_map_key_value(m)
# output: {1: 'A', 2: 'B', 3: 'C'}

参考:

  • 2gua-几个Python代码片段

合并字典值

>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})

字典的增加

用 update 方法往已有字典中增加键值对:

deploy_info=dict()
for idx, row in raw_data.iterrows():
    temp=dict()
    version = row['version']
    app_comp_name = row['app_comp_name']
    pkg_name = "{}_{}.tar.gz".format(app_comp_name, version)
    time.sleep(2)
    data = get_verify_value(api_url,pkg_name)
    temp = {
        deploy_history_id:{
            'app_comp_name':app_comp_name,
            'version':version,
            'pkg_name':pkg_name,
            'data':data
        }
    }
    deploy_info.update(temp)

字符串相关

索引

tag='hx/mitaka_compute/12.0.0'
[m.start() for m in re.finditer('/',tag)]

参考:

  • 在Python中查找所有出现的子字符串

将百分号的百分比字符串转为数字

p="75%"
float(p.strip('%'))/100

参考:

  • Convert to numeric Python

剔除分隔符

通常做法:

''.join('A|B|C|D|E|F|G'.split('|'))
# output: 'ABCDEFG'

用 itertools.islice ,因为可以节选字符串:

import itertools
''.join(itertools.islice('A|B|C|D|E|F|G', 6, None, 2))
# output: 'DEFG'
''.join(itertools.islice('A|B|C|D|E|F|G', 0, None, 2))
# output: ''ABCDEFG'

美观打印

import pprint as pp
animals = [{'animal': 'dog', 'legs': 4, 'breeds': ['Border Collie', 'Pit Bull', 'Huskie']}, {'animal': 'cat', 'legs': 4, 'breeds': ['Siamese', 'Persian', 'Sphynx']}]
pp.pprint(animals, width=1)
# Out
[{'animal': 'dog',
  'breeds': ['Border '
             'Collie',
             'Pit '
             'Bull',
             'Huskie'],
  'legs': 4},
 {'animal': 'cat',
  'breeds': ['Siamese',
             'Persian',
             'Sphynx'],
  'legs': 4}]

width参数指定一行上最大的字符数。设置width为1确保字典打印在单独的行

文件读写

基本文件读 txt

# Note: rb opens file in binary mode to avoid issues with Windows systems
# where 'rn' is used instead of 'n' as newline character(s).
# A) Reading in Byte chunks
reader_a = open("file.txt", "rb")
chunks = []
data = reader_a.read(64)  # reads first 64 bytes
while data != "":
    chunks.append(data)
    data = reader_a.read(64)
if data:
    chunks.append(data)
print(len(chunks))
reader_a.close()
# B) Reading whole file at once into a list of lines
with open("file.txt", "rb") as reader_b:   # recommended syntax, auto closes
    data = reader_b.readlines() # data is assigned a list of lines
print(len(data))
# C) Reading whole file at once into a string
with open("file.txt", "rb") as reader_c:
    data = reader_c.read() # data is assigned a list of lines
print(len(data))
# D) Reading line by line into a list
data = []
with open("file.txt", "rb") as reader_d:
    for line in reader_d:
        data.append(line)
print(len(data))

json 读写json文件

  • json.loads()是将str转化成dict格式,json.dumps()是将dict转化成str格式。
  • json.load()和json.dump()也是类似的功能,只是与文件操作结合起来了。
# 解码
import json
with open('build_info.json','r') as f:
    array = json.load(f)
print(array)

在编码JSON的时候,还有一些选项很有用。 如果你想获得漂亮的格式化字符串后输出,可以使用 json.dumps() 的 indent 参数。 它会使得输出和pprint() 函数效果类似:

>>> print(json.dumps(data))
{"price": 542.23, "name": "ACME", "shares": 100}
>>> print(json.dumps(data, indent=4))
{
    "price": 542.23,
    "name": "ACME",
    "shares": 100
}
>>>

保存为 json 文件:

# 编码
import json
a = {"name":"michael"}
with open("demo.json","w") as f:
	json.dump(a, f, indent=4)
  • CookBook-6.2 读写JSON数据
  • 简书-Python: json模块实例详解
  • 官宣-json — JSON encoder and decoder
  • Reading JSON file with Python 3
  • What is the difference between json.load() and json.loads() functions in Python?

时间日期

基本时间(time)和日期(date)

import time
# print time HOURS:MINUTES:SECONDS
# e.g., '10:50:58'
print(time.strftime("%H:%M:%S"))
# print current date DAY:MONTH:YEAR
# e.g., '05/01/2019'
print(time.strftime("%d/%m/%Y"))
# Out
15:18:03
05/01/2019

字符串和日期的相互转换

strptime 是将字符串转换为 datetime,其实这个方法的全称是 “string parse time”,叫做字符串解析成时间,重点在解析(parse):

from datetime import datetime
date_obj = datetime.strptime('2018-10-15 20:59:29', '%Y-%m-%d %H:%M:%S')
print(type(date_obj),date_obj)
# Out
<class 'datetime.datetime'> 2018-10-15 20:59:29

strftime 是将 datetime 转换为字符串,全称是 “string format time”,翻译过来就是将字符串的形式来格式化时间,重点在格式化(format),使之以一种可读的字符串形式返回:

from datetime import datetime
date_obj = datetime.now()
date_string = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(type(date_string),date_string)
# Out
<class 'str'> 2019-01-05 18:41:04

参考:

  • 3分钟学会一个小技巧

编码相关

Python Requests 编码问题

  • requests github issue

下载

Python下载文件

  • urlretrieve

Python根据url下载目录或者文件

def download_package(self, package_url):
    print("start download_build_result")
    if not package_url.endswith("/"):
        package_url += '/'
    cmd = "wget -c -r -nd -np -P %s %s" % ("output", package_url)
    print(cmd)
    os.system(cmd)
    print(os.getcwd())
    print("finish download_build_result")

数据处理

Python Pandas处理Excel数据

逐行处理数据 iterrows

for idx, row in data.iterrows():
    project_name=row['projectName']
    tag_name=row['tagName']

Pandas追加模式写入csv文件

data = pd.DataFrame([[1,2,3]])
csv_headers=['A','B','C']
data.to_csv('./Marvel3_yingpping.csv', header=csv_headers, index=False, mode='a+', encoding='utf-8')
data = pd.DataFrame([[4,5,6]])
data.to_csv('./Marvel3_yingpping.csv', header=False, index=False, mode='a+', encoding='utf-8')
data = pd.DataFrame([[7,8,9]])
data.to_csv('./Marvel3_yingpping.csv', header=False, index=False, mode='a+', encoding='utf-8')

Python-CSV-Excel

  • Python Pandas iterrows method
for idx, row in data.iterrows():
    project_name=row['projectName']
    tag_name=row['tagName']

to_csv表格中文乱码

ipython中直接打印df,中文没有乱码,但是 to_csv 方法存储时,中文有乱码。

df.to_csv('file.csv',encoding='utf-8-sig')

 

参考:

  • Pandas df.to_csv(“file.csv” encode=“utf-8”) still gives trash characters for minus sign
  • 关于pandas中,to_csv函数输出的utf8数据用Excel打开是乱码

itero

看题目:

  • python数据处理,字典生成的一个问题 答案中有位前辈用这个用的炉火纯青啊!

Shell/Linux 操作相关

Python运行shell命令的函数:

def run(cmd_str, fatal=True):
    # this is not a good implement
    log.command(log.term.cmd(cmd_str))
    ret = os.system(cmd_str)
    if ret is not 0:
        if fatal:
            log.error('[ERROR] run cmd: %s failed', cmd_str)
            os._exit(1)
        else:
            log.info('[INFO] %s is not fatal' % cmd_str)

调用外部的命令

#
import subprocess
subprocess.call(['mkdir', 'empty_folder'])
# 运行一条命令并输出得到的结果
output = subprocess.check_output(['ls', '-l'])
# 上面的调用是阻塞的
# 如果运行shell中内置的命令,如cd或者dir,需要指定标记shell=True
output = subprocess.call(['cd', '/'], shell=True)
# 对于更高级的用例,可以使用 Popen constructor。

Python 3.5引进了一个新的run函数,它的行为与call和check_output很相似。如果你使用的是3.5版本或更高版本,看一看run的文档,里面有一些有用的例子。否则,如果你使用的是Python 3.5以前的版本或者你想保持向后兼容性,上面的call和check_output代码片段是你最安全和最简单的选择

参考:

计算文件的校验值

可以计算文件的 md5 、 sha256 等值

# https://pymotw.com/3/hashlib/index.html#module-hashlib
def get_verify_value(file_path, verify_type):
    """
    计算指定文件的校验值
    :param file_path: 文件路径
    :param verify_type: 校验值类型,md5 sha256 等等
    :return:
    """
    h = hashlib.new(verify_type)
    if not file_path:
        return None
    with open(file_path, 'rb') as f:
        for block in iter(lambda: f.read(4096), b""):
            h.update(block)
    return h.hexdigest()

性能相关

脚本的运行时间

import time
start_time = time.clock()
for i in range(10000000):
    pass
elapsed_time = time.clock() - start_time
print("Time elapsed: {} seconds".format(elapsed_time))
# Out
Time elapsed: 0.30121700000000007 seconds
import timeit
elapsed_time = timeit.timeit('for i in range(10000000): pass', number=1)
print("Time elapsed: {} seconds".format(elapsed_time))
# Out
Time elapsed: 0.2051873060000844 seconds

计算运行时间

class Timer(object):
    def __enter__(self):
        self.error = None
        self.start = time.time()
        return self
    def __exit__(self, type, value, tb):
        self.finish = time.time()
        if type:
            self.error = (type, value, tb)
    def duration(self):
        return self.finish - self.start
with Timer() as timer:
    func()
timer.duration()
# Out
0.29994797706604004

参考:

  • 优快云- python代码片段

目录、路径相关

基本目录文件操作

import os
import shutil
import glob
# working directory
c_dir = os.getcwd()                 # show current working directory
os.listdir(c_dir)                   # shows all files in the working directory
os.chdir('~/Data')                  # change working directory
# get all files in a directory
glob.glob('/Users/sebastian/Desktop/*')
# e.g.,  ['/Users/sebastian/Desktop/untitled folder', '/Users/sebastian/Desktop/Untitled.txt']
# walk
tree = os.walk(c_dir)
# moves through sub directories and creates a 'generator' object of tuples
# ('dir', [file1, file2, ...] [subdirectory1, subdirectory2, ...]),
#    (...), ...
#check files: returns either True or False
os.exists('../rel_path')
os.exists('/home/abs_path')
os.isfile('./file.txt')
os.isdir('./subdir')
# file permission (True or False
os.access('./some_file', os.F_OK) # File exists? Python 2.7
os.access('./some_file', os.R_OK) # Ok to read? Python 2.7
os.access('./some_file', os.W_OK) # Ok to write? Python 2.7
os.access('./some_file', os.X_OK) # Ok to execute? Python 2.7
os.access('./some_file', os.X_OK | os.W_OK) # Ok to execute or write? Python 2.7
# join (creates operating system dependent paths)
os.path.join('a', 'b', 'c')
# 'a/b/c' on Unix/Linux
# 'a\b\c' on Windows
os.path.normpath('a/b/c') # converts file separators
# os.path: direcory and file names
os.path.samefile('./some_file', '/home/some_file')  # True if those are the same
os.path.dirname('./some_file')  # returns '.' (everythin but last component)
os.path.basename('./some_file') # returns 'some_file' (only last component
os.path.split('./some_file') # returns (dirname, basename) or ('.', 'some_file)
os.path.splitext('./some_file.txt') # returns ('./some_file', '.txt')
os.path.splitdrive('./some_file.txt') # returns ('', './some_file.txt')
os.path.isabs('./some_file.txt') # returns False (not an absolute path)
os.path.abspath('./some_file.txt')
# create and delete files and directories
os.mkdir('./test')  # create a new direcotory
os.rmdir('./test')  # removes an empty direcotory
os.removedirs('./test') # removes nested empty directories
os.remove('file.txt')   # removes an individual file
shutil.rmtree('./test') # removes directory (empty or not empty)
os.rename('./dir_before', './renamed') # renames directory if destination doesn't exist
shutil.move('./dir_before', './renamed') # renames directory always
shutil.copytree('./orig', './copy') # copies a directory recursively
shutil.copyfile('file', 'copy')     # copies a file
# Getting files of particular type from directory
files = [f for f in os.listdir(s_pdb_dir) if f.endswith(".txt")]
# Copy and move
shutil.copyfile("/path/to/file", "/path/to/new/file")
shutil.copy("/path/to/file", "/path/to/directory")
shutil.move("/path/to/file","/path/to/directory")
# Check if file or directory exists
os.path.exists("file or directory")
os.path.isfile("file")
os.path.isdir("directory")
# Working directory and absolute path to files
os.getcwd()
os.path.abspath("file")

参考:

  • 斗大的熊猫-收集的有用的 Python 代码片段

Python 删除文件夹

def onerror(func, path, exc_info):
    """
    Error handler for ``shutil.rmtree``.
    If the error is due to an access error (read only file)
    it attempts to add write permission and then retries.
    If the error is for another reason it re-raises the error.
    Usage : ``shutil.rmtree(path, onerror=onerror)``
    """
    import stat
    if not os.access(path, os.W_OK):
        # Is the error an access error ?
        os.chmod(path, stat.S_IWUSR)
        func(path)
    else:
        raise

参考:

  • shutil.rmtree fails on Windows with ‘Access is denied’

Python 切换目录

执行完,返回之前目录

import contextlib
@contextlib.contextmanager
def cdir(path):
    prev_cwd = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(prev_cwd)

用法:

with cdir(path):
    func()

搜索指定目录下的文件

将指定目录及其子目录下的文件搜索出来:

def find_file(start_path, name):
    """
    search the files of name from the dir start_path,存放的是搜索文件的路径
    :param start_path: the search scope of dir
    :param name: the name of search file
    :return: set of files path
    """
    files_path = set()
    for rel_path, dirs, files in os.walk(start_path):
        # if name in files:
        for f in files:
            if name in f:
                full_path = os.path.join(start_path, rel_path, f)
                path = os.path.normpath(os.path.abspath(full_path))
                files_path.add(path)
    return files_path

只列出文件夹下的文件夹

[ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
filter(os.path.isdir, os.listdir(os.getcwd()))
  • How to list only top level directories in Python?

Python Path相关问题

os.path.split(r"C:\foo\bar\file_name.txt")

 

  • 格式化文件路径

数据库

MySQL 数据库

db = MySQLdb.connect("localhost","your_username","your_password","your_dbname")
cursor = db.cursor()
sql = "select Column1,Column2 from Table1"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
    print row[0]+row[1]
db.close()

参考:

  • 斗大的熊猫-最常用的Python代码片段

MongoDB

uri="mongodb://admin:admin@xxx.xxx.xxx.xxx:27017,xxx.xxx.xxx.xxx:27018,xxx.xxx.xxx.xxx:27019/test"
client=pymongo.MongoClient(uri,replicaSet='noah-cluster',readPreference='primaryPreferred')
db=client.get_default_database()
decouple_history=db.rpm_decouple_release_history_info
pprint(decouple_history.find_one({'service_name':'test'}))
Qt代码-军用仿真系统基础框架 ui->mapClickLabel->setText(QString("地图点击:(%.1f, %.1f)米").arg(worldPos.x()).arg(worldPos.y()));emit simulationEvent(QString("添加实体: %1 (ID: %2)").arg(attr.name).arg(entity.id()));// 像素坐标→世界坐标(米) 阅读详情

相关推荐

逆变器方案(工频全套)工频正弦波逆变器开发板全套设计资

逆变器方案(工频全套)工频正弦波逆变器开发板,24V-72V通用12只TO-247封装MOS管,额定输出功率6500W以下;配有触摸屏操作界面,运行数据一目了然,带市电互补UPS功能,可选择电池优先或市电有限工作,我们的开发板均从实战角度出发,让您的学习更便捷,包含全套设计资料,PCB.原理图.源代码,程序均有中文注释,MCU选用美国微芯公的PIC-8位单片机,民用数字电源首选单片机,抗干扰能力强,运行稳定。...

m0_73494033的博客 895

Python 代码片段收藏

list 列表相关 list 中最小值、最大值 import operator values = [1, 2, 3, 4, 5] min_index, min_value = min(enumerate(values), key=operator.itemgetter(1)) max_index, max_value = max(enumerate(values), key=operato...

weixin_33911824的博客 433

TwinCAT3实战:从零搭建倍福PLC的Modbus-TCP Server

本文详细介绍了如何使用TwinCAT3从零搭建倍福PLC的Modbus-TCP Server,包括环境准备、工程配置、参数设置、客户端连接测试及常见问题排查。通过实战步骤和实用技巧,帮助工程师快速掌握倍福PLC与Modbus-TCP的通信实现,提升工业自动化项目的开发效率。

weixin_30797199的博客 174

通过UIPATH对Excel信息整合过程中出现单元格格式不匹配的一种解决方法

今天博主在工作中遇到了一个问题,通过"Read Range"这个活动获取的单元格中如果存在百分号,存入DataTable表中,再写入一个新的Excel表中,这个百分号就已经变成小数。 通过"Log Message"这个"Activities"活动发现,其实在获取数据的时候,这个百分号就已经变成小数了。 开始博主的想法主要有三个:1、希望通过机器人来打开这个Excel,通过鼠标点击来设置单元格格式,使之能够在获取数据的时候就已经变成百分数;2、在"Activities"活动查看是否有直接可以获取单元格的格

Chansyia的博客 2408

YOLOv8实例分割实战:从LabelMe标注到模型训练全流程(附完整代码)

本文详细介绍了YOLOv8实例分割的完整实战流程,涵盖从使用LabelMe进行数据标注、格式转换,到构建数据集、配置参数并完成模型训练的全过程。文章提供了详尽的代码示例和常见问题解决方案,旨在帮助开发者高效掌握YOLOv8实例分割技术,快速应用于实际项目。

java5的博客 816

cellchat安装

cellchat

m0_65188455的博客 5451

[Pyhton·Pandas]关于pandas使用groupby后apply报错TypeError: unhashable type: ‘list‘这件事

我有一个DataFrame,如下 df = pd.DataFrame(data=[[[1,2],[3,4],5,6],[[1,2],[0,0],0,0]],columns=['a','b','c','d']) df 输出: a b c d 0 [1,2] [3,4] 5 6 1 [1,2] [0,0] 0 0 然后我groupby再apply df.groupby('a').apply(lambda g:g) 报错! ...... pandas\_libs\hashtable_c

梦痕 2186

避开模板匹配的坑:OpenCVSharp中边缘梯度算法的优化实践

本文深入探讨了OpenCVSharp中边缘梯度算法在模板匹配中的优化实践,解决了传统方法在尺度变化、角度旋转和光照差异下的局限性。通过Sobel算子提取边缘梯度特征,结合轮廓检测和多尺度匹配策略,显著提升了匹配的鲁棒性和准确性。文章还分享了并行计算、内存访问优化等实战技巧,适用于工业检测和自动化识别场景。

http9protocoller的博客 199

Python人一定要知道的13个代码片段(超有用,拒绝标题党!)

Python人一定要知道的13个超有用的代码片段,这些日常片段将优化你的Python编程代码

Python_9521的博客 561

WINDOWS下SIP拨号的实现

在WIN10上拨打SIP电话  由于我的交换原理实验有一个是关于SIP的抓包的。而之前从未接触过SIP,所以在如何完成一次SIP拨号上遇到了不少问题,查了好多资料都没有完整的或者写的很清楚的,这里就对那些资料做一个总结,给出一个比较完善的解决方案,一来是记录此次实验的收获,而来也可能为其他有同样困惑的人解惑。  废话不多说直接开始。首先是下载一个可以拨打SIP电话的客户终端,这里我选择的是MicroSIP, 下载红圈内的文件,下载好之后直接一路安装即可,没有什么特别注意的地方。  安装好客户端之后,就需要注

weixin_43918519的博客 3808

AI工程化之生成式UI & A2UI(二)

本文介绍了生成式UI框架A2UI的架构设计与核心实现。项目采用AI协作开发模式,通过ATDD(AI驱动的测试驱动开发)确保代码质量。前端SDK基于zustand实现框架无关的状态管理,包含协议解析器、存储管理、渲染器等核心模块。重点展示了基础store构建、A2UI协议解析器的实现过程,包括mock数据准备、测试用例生成和可视化调试。项目采用monorepo管理,利用vite实现高效开发构建。整个系统设计遵循模块化原则,通过清晰的接口定义实现各组件解耦,为后续功能扩展打下基础。

qq_34306228的博客 407

超级实用的python代码片段汇总和详细解析(16个)

如果你想要对抓取到的数据进行进一步的处理或分析,你还需要编写更多的代码来实现这些功能。你可能需要添加一些额外的逻辑来确认你要结束的进程确实是你想要的,或者至少确保你不会意外地结束重要的系统进程。用于将多个 Excel 工作表(sheets)合并到一个单一的 DataFrame 中,并将该 DataFrame 保存到一个新的 Excel 文件中。用于在给定的图像上添加水印。当你调用这个函数并传入一个PDF文件路径列表和一个输出文件路径时,它将读取所有输入文件,并将它们的页面合并到一个单一的输出文件中。

汉阳Hann's Home 1952

STM32实战开发(128):智能位移检测 - 使用STM32实现位移检测

STM32作为一款功能强大的微控制器,由于其出色的处理能力、丰富的外设接口和低功耗特点,成为实现智能位移检测系统的理想选择。未来,可以通过结合更多传感器、多种数据处理算法以及云平台技术,进一步提升系统的智能化水平,优化位移测量的精度和稳定性。本篇博客将介绍如何使用STM32微控制器实现智能位移检测系统,涉及硬件设计、传感器选择、软件开发等多个方面,提供详细的设计步骤,并给出完整的代码示例,帮助开发者快速搭建智能位移检测系统。蜂鸣器连接到STM32的GPIO端口,当位移超过设定的阈值时,蜂鸣器发出警报。

2201_76125393的博客 901

13 个非常有用的 Python 代码片段,建议收藏!

作者|周萝卜来源 |萝卜大杂烩今天我们主要来介绍应用程序当中的通用 Python 代码片段,一起进步吧Lists Snippets 我们先从最常用的数据结构列表开始№1:将两个列表合并成一个字典假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问...

AI科技大本营 901

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

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

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【Python】13 个非常有用的 Python 代码片段,建议收藏!

今天我们主要来介绍应用程序当中的通用 Python 代码片段,一起进步吧Lists Snippets 我们先从最常用的数据结构列表开始№1:将两个列表合并成一个字典假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问题但是为了解决这个问题,我们需要考虑...

fengdu78的博客 265

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

20个最频繁使用的Python代码片段!建议收藏备用。

在本文中,将分享20 个 Python 代码片段,以帮助你应对日常编程挑战。你可能已经知道其中一些片段,但有些其他片段对你来说可能是新的。赶紧使用这些有用的 Python 代码片段提升你的编程技能吧。

weixin_52994140的博客 461

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

13 个非常有用的 Python 代码片段,建议收藏

大家好,今天我主要来介绍程序当中的通用 Python 代码片段,大家可以收藏、点赞、关注,一起进步吧废话不多说,我们开始吧,技术交流文末获取我们先从最常用的数据结构列表开始假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问题但是为了解决这个问题,我们需要考虑几个限制,比如两个列表的大小,两个列表中元素的类型,以及其中是否有重复的元素,尤其是我们将使用的元素作为 key 时。我们可以通过

Python数据挖掘 737

30秒内便能学会的30个超实用Python代码片段

许多人在数据科学、机器学习、web开发、脚本编写和自动化等领域中都会使用Python,它是一种十分流行的语言。 Python流行的部分原因在于简单易学。 本文将简要介绍30个简短的、且能在30秒内掌握的代码片段。 1. 唯一性 以下方法可以检查给定列表是否有重复的地方,可用set()的属性将其从列表中删除。 ...

读芯术的博客 5万+

Python开发者必备:50个提升开发效率的实用代码片段(建议收藏)

🙏徐白知识星球📚徐白知识星球我会持续输出高质量的前端技术文章,分享实战经验和技术心得。共同成长欢迎在评论区留言交流有问题随时后台私信定期举办技术分享会更多精彩内容持续更新中…让我们一起在技术的道路上携手前行!💪。

徐白知识星球 1417

13 个非常有用的 Python 代码片段,赶快收藏~

今天我们主要来介绍应用程序当中的通用 Python 代码片段,一起进步吧\我们先从最常用的数据结构列表开始假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值。这是在用 Python 编写代码时经常遇到的一个非常常见的问题但是为了解决这个问题,我们需要考虑几个限制,比如两个列表的大小,两个列表中元素的类型,以及其中是否有重复的元素,尤其是我们将使用的元素作为 key 时。我们可以通过使用 zip 等内置函数来解决这些问题 №2:将两个或多个列表

sixqingfeng的博客 286

Python有哪些实用的值得收藏的代码片段

我们在写代码的时候往往会遇到各种的小问题,尤其是一些反复使用的小段代码(不是库或者函数的用法技巧什么的),这里,给大家分享下个人收藏的一些代码片段,也欢迎大家一起分享! 1、 文件命名 有时候我们做好一个爬虫代码,用抓取的数据名称命名并保存文件,但往往在这里出错,然后代码就停止运行了,很是烦人!那么我们可以用下面的函数!最后,如果你的时间不是很紧张,并且又想快速的提高,最重要的是不怕吃苦,建议你可以联系维:762459510 ,那个真的很不错,很多人进步都很快,需要你不怕吃苦哦!大家可以去添加上看一下~ .

zihong523的博客 197

20 个解决日常问题的 Python 代码片段,赶紧收藏

在本文中,将分享20 个 Python 代码片段,以帮助你应对日常编程挑战。你可能已经知道其中一些片段,但有些其他片段对你来说可能是新的。赶紧使用这些有用的 Python 代码片段提升你的编程技能吧。

weixin_56659172的博客 1412

25个针对日常问题的有用Python代码片段

Python无疑是Web开发、应用程序开发、安全和数据科学领域的顶级编程语言之一。 为了让你的 Python编码既省时又简单,这里收集了一些Python代码片段。

2301_78217634的博客 873

12个Python代码片段,帮你完成工作自动化!

从自动化发送带附件的电子邮件到检索Wi-Fi密码、下载油管视频等等,这些代码片段将使您能够无缝完成任务。此代码片段使用subprocess库来检索计算机上保存的Wi-Fi密码,简化网络管理。Python,一种多功能的编程语言,提供了各种功能和库来有效地自动化任务。此代码片段演示了如何使用smtplib和email库发送带附件的电子邮件。因篇幅有限,仅展示部分资料,需要点击下方链接即可前往获取。因篇幅有限,仅展示部分资料,需要点击下方链接即可前往获取。在本文中,我们将探索12个高级Python代码片段,

Libra1313的博客 497

Latex插入Python代码片段

在latex中插入Python代码片段的简便快速方法是用minted包,相比之下listings包略显麻烦,而且用这个包插入python代码需要自己设定许多参数,不是很友好。

liuz_notes的博客 6789

你必须熟练使用的30个有用Python代码片段

Python是数据科学和机器学习、web开发、脚本编写、自动化等领域中许多人使用的最流行的语言之一。这种流行的部分原因是它简单易学。如果您正在阅读本文,那么您很可能已经在使用Python...

tongtongjing1765的博客 1922
上一篇: 教你 如何用Python开发一个简单的区块链数据结构!
下一篇: Python数据分析之Pandas读写外部数据文件!
普通网友
博客等级 码龄7年 438粉丝 263原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值