百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

【AI&ML】如何使用Google Colaboratory进行视频处理

toyiye 2024-09-06 00:09 4 浏览 0 评论

介绍

您是否知道一组计算机算法可以处理视频流,使其能够检测犯罪活动,控制交通拥堵,甚至自动检测体育广播中的事件?由于机器学习(ML)的应用,从简单视频中获取如此多数据的想法似乎并不现实。在本文中,我们希望分享我们的经验,将机器学习算法的预构建逻辑应用于视频的对象检测和分割。

特别是,我们讨论了如何配置Google Colaboratory以通过机器学习解决视频处理任务。您将学习如何使用此Google服务及其提供的免费NVIDIA Tesla K80 GPU,以实现您在训练神经网络方面的目标。本文对于熟悉机器学习并考虑使用图像识别和视频处理的人员非常有用。

具有有限硬件资源的图像处理

Apriorit的任务是在机器学习(ML)算法的帮助下识别视频录制中的人。我们决定从基础开始。首先,让我们考虑一下视频录制的实际情况。

从技术角度来看,任何视频录制都包含一系列以视频编解码器压缩的特定格式的静止图像。因此,对视频流的对象识别归结为将流分割成单独的图像或帧,并将预先训练的ML图像识别算法应用于它们。

为此,我们决定使用Mask_R-CNN存储库中的神经网络对单个图像进行分类。存储库包含Python 3,TensorFlow和Keras上的卷积神经网络的实现。让我们看看这个计划的结果。

Mask_RCNN示例

我们开发并实现了一个简单的样本,Mask_RCNN它将图片作为输入和识别对象。我们根据Mask_R-CNN存储库中的demo.ipynb描述创建了一个示例。这是我们的示例代码:

import os, sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
# Root directory of the project
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
config = InferenceConfig()
config.display()
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])

在此示例中,/ content / drive / My Drive / Colab Notebooks / MRCNN_pure是使用Mask_R-CNN到我们的存储库的路径。结果,我们得到以下结果:

2019年将有创记录的机器学习(ML)和深度学习会议,以下列表提供了即将召开的ML的会议描述,可以帮助您决定参加那个会议,赞助或者提供会谈。

这部分演示代码通过images文件夹查看,随机选择一个图像,然后将其加载到我们的神经网络模型中进行分类:

# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
# Run detection
results = model.detect([image], verbose=1)

让我们修改Mask_R-CNN样本,使其识别images文件夹中的所有图像:

# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
for file_name in file_names:
image = skimage.io.imread(os.path.join(IMAGE_DIR, file_name))
# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])

运行演示代码五分钟后,控制台显示以下输出:

...
Processing 1 images
image shape: (415, 640, 3) min: 0.00000 max: 255.00000 uint8
molded_images shape: (1, 1024, 1024, 3) min: -123.70000 max: 151.10000 float64
image_metas shape: (1, 93) min: 0.00000 max: 1024.00000 float64
anchors shape: (1, 261888, 4) min: -0.35390 max: 1.29134 float32
Segmentation fault (core dumped)

最初,我们在具有Intel Core i5和8GB RAM的计算机上运行演示代码,而不使用独立显卡。代码每次都在不同的地方崩溃,但最常见的是,它在内存分配期间在TensorFlow框架中崩溃。此外,在图像识别过程中运行任何其他软件的任何尝试都会使计算机减慢到无用的程度。

因此,我们遇到了一个严重的问题:任何熟悉ML的实验都需要强大的显卡和更多的硬件资源。没有这个,我们在识别大量图像时无法执行任何其他任务。

通过Google Colaboratory增加我们的硬件资源

我们决定使用Google 的Colaboratory服务扩展我们的硬件资源,也称为Colab。Google Colab是一款免费的云服务,可提供CPU和GPU以及预配置的虚拟机实例。具体来说,谷歌为NVIDIA Tesla K80 GPU提供了12GB的专用视频内存,这使得Colab成为实验神经网络的完美工具。

在解释如何使用此Google服务之前,我们想强调其他有益的Colaboratory功能。

通过选择Colab进行ML实验,您将得到:

● 支持Python 2.7和Python 3.6,因此您可以提高编码技能

● 能够使用Jupyter笔记本,以便您可以创建,编辑和共享.ipynb文件

● 能够使用本地计算机连接到Jupyter运行时

● 许多预安装的库,包括TensorFlow,Keras和OpenCV,以及与Google Colaboratory中的自定义库进行交互的可能性

● 上传功能,以便您可以添加训练有素的模型

● 与GitHub集成,以便您可以加载公共GitHub笔记本或将Colab文件的副本保存到GitHub

● 使用像matplotlib这样流行的库进行简单的可视化

● 可用于参数化代码的表单

● 能够将Google Colab笔记本电脑存储在您的Google云端硬盘中

要开始使用Google Colab GPU,您只需要提供对在Docker容器中实现的.ipynb脚本的访问权限。Docker容器仅分配给您12个小时。您创建的所有脚本默认存储在Colab笔记本部分的Google云端硬盘中,该部分会在您连接到Colaboratory时自动创建。在12小时到期后,容器中的所有数据都将被删除。您可以将Google云端硬盘安装到容器中并使用它来避免这种情况。否则,Docker镜像的文件系统将仅在有限的时间段内可用。

配置Google Colab

我们首先解释一下如何创建.ipynb笔记本。在此处打开Goog??le Colaboratory ,选择Google Drive部分,然后点击NEW PYTHON 3 NOTEBOOK:

通过单击文件名重命名您的笔记本。现在您需要选择硬件。要执行此操作,只需转到"编辑"部分,找到"笔记本设置",选择GPU作为硬件加速器,然后单击"保存"保存更改。

保存新设置后,将为您提供带有独立显卡的Docker容器。您将在页面右上角的" 已连接 "消息中收到有关此消息的通知:

如果您没有看到此消息,请选择" 连接到托管运行时"。

现在,您可以将Google云端硬盘安装到此容器,以便重新定位源代码并将工作结果保存在容器中。要执行此操作,只需在第一个表格单元格中复制下面的代码,然后按"播放"按钮(或Shift + Enter)。

通过运行此代码安装Google云端硬盘:

from google.colab import drive
drive.mount('/content/drive')

您将收到授权请求。单击链接,授权,复制验证码,将其粘贴到.ipynb脚本的文本框中,然后按Enter键。如果授权成功,您的Google云端硬盘将安装在路径/内容/驱动器/我的云端硬盘下。要关注文件树,请在左侧菜单中选择" 文件 "。

现在您拥有一个Docker容器,其中包含Tesla K80 GPU,您的Google Drive作为文件存储,以及.ipynb笔记本,用于执行脚本。

使用 Google Colab进行对象识别

现在我们将描述如何在Google Colab中运行Mask_R-CNN样本以进行对象识别。我们按照/ content / drive / My Drive / Colab笔记本/路径将Mask_RCNN存储库上传到我们的Google云端硬盘。

然后我们将示例代码添加到.ipynb脚本中。执行此操作时,不要忘记更改您的Mask_RCNN文件夹的路径,如下所示:

os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")

如果您做的一切正确,代码执行的结果将为您提供一个图像,其中检测和识别所有对象。

您还可以修改示例代码以使其处理所有测试图像:

import os, sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
# Root directory of the project
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
config = InferenceConfig()
config.display()
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
for file_name in file_names:
image = skimage.io.imread(os.path.join(IMAGE_DIR, file_name))
# Run detection
results = model.detect([image], verbose=1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])

使用Google Colab中的对象检测,我们可以快速收到识别对象的结果,而我们的计算机即使在图像识别过程中也能继续正常运行。

使用Google Colab进行视频处理

让我们看看我们如何应用此方法来识别视频流中的人物。我们将测试视频文件上传到Google云端硬盘。为了训练我们的脚本使用视频流,我们使用了OpenCV,一种流行的开源计算机视觉库。

我们不需要在一个图像上读取和实现识别模型的整个代码。因此,而不是打开的视频文件,我们运行的视频流和它的指针移动到1000 个,因为没有对象在记录的介绍认识框架。

import cv2
...
VIDEO_STREAM = "/content/drive/My Drive/Colab Notebooks/Millery.avi"
VIDEO_STREAM_OUT = "/content/drive/My Drive/Colab Notebooks/Result.avi"
...
# initialize the video stream and pointer to output video file
vs = cv2.VideoCapture(VIDEO_STREAM)
writer = None
vs.set(cv2.CAP_PROP_POS_FRAMES, 1000);
然后我们用神经网络模型处理20,000帧。OpenCV对象允许我们使用该read()方法从视频文件中逐帧获取图像。将接收到的图像传递给model.detect()方法,并使用该visualize.display_instances()函数显示结果。
但是,我们遇到了一个问题:display_instances()Mask_RCNN存储库中的函数反映了图像中检测到的对象,但图像没有返回。我们决定简化display_instances() 函数并使其返回带有显示对象的图像:
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = visualize.random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.shape[0] == masks.shape[-1] == ids.shape[0]
for i, color in enumerate(colors):
if not np.any(boxes[i]):
continue
y1, x1, y2, x2 = boxes[i]
label = names[ids[i]]
score = scores[i] if scores is not None else None
caption = '{} {:.2f}'.format(label, score) if score else label
mask = masks[:, :, i]
image = visualize.apply_mask(image, mask, color)
image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
image = cv2.putText(
image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2
)
return image
处理完毕后,帧应该重新绑定到一个新的视频文件中。我们也可以使用OpenCV库来完成此操作。我们需要做的就是VideoWriter从OpenCV库中分配对象:
fourcc = cv2.VideoWriter_fourcc(*"XVID")
writer = cv2.VideoWriter(VIDEO_STREAM_OUT, fourcc, 30,
(masked_frame.shape[1], masked_frame.shape[0]), True)

使用我们为输入提供的视频类型。我们在以下帮助下获得视频文件类型ffprobecommand:

ffprobe Result.avi
...
Duration: N/A, start: 0.000000, bitrate: N/A
Stream #0:0: Video: mpeg4 (Simple Profile) (XVID / 0x44495658),
yuv420p, 640x272 [SAR 1:1 DAR 40:17], 30 fps, 30 tbr, 30 tbn, 30 tbc

接收的对象可用于每帧记录:writer.write(masked_frame)。

在脚本的开头,我们需要指定目标视频文件的路径以进行处理:VIDEO_STREAM和VIDEO_STREAM_OUT。

这是我们为视频识别开发的完整脚本:

from google.colab import drive
drive.mount('/content/drive')
import os, sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import cv2
from matplotlib.patches import Polygon
os.chdir("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
sys.path.append("/content/drive/My Drive/Colab Notebooks/MRCNN_pure")
VIDEO_STREAM = "/content/drive/My Drive/Colab Notebooks/Millery.avi"
VIDEO_STREAM_OUT = "/content/drive/My Drive/Colab Notebooks/Result.avi"
# Root directory of the project
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")
class InferenceConfig(coco.CocoConfig):
# Set batch size to 1 since we'll be running inference on
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = visualize.random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.shape[0] == masks.shape[-1] == ids.shape[0]
for i, color in enumerate(colors):
if not np.any(boxes[i]):
continue
y1, x1, y2, x2 = boxes[i]
label = names[ids[i]]
score = scores[i] if scores is not None else None
caption = '{} {:.2f}'.format(label, score) if score else label
mask = masks[:, :, i]
image = visualize.apply_mask(image, mask, color)
image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
image = cv2.putText(
image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2
)
return image
config = InferenceConfig()
config.display()
# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)
# COCO Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']
# Initialize the video stream and pointer to output video file
vs = cv2.VideoCapture(VIDEO_STREAM)
writer = None
vs.set(cv2.CAP_PROP_POS_FRAMES, 1000);
i = 0
while i < 20000:
# read the next frame from the file
(grabbed, frame) = vs.read()
i += 1
# If the frame was not grabbed, then we have reached the end
# of the stream
if not grabbed:
print ("Not grabbed.")
break;
# Run detection
results = model.detect([frame], verbose=1)
# Visualize results
r = results[0]
masked_frame = display_instances(frame, r['rois'], r['masks'], r['class_ids'],
class_names, r['scores'])
# Check if the video writer is None
if writer is None:
# Initialize our video writer
fourcc = cv2.VideoWriter_fourcc(*"XVID")
writer = cv2.VideoWriter(VIDEO_STREAM_OUT, fourcc, 30,
(masked_frame.shape[1], masked_frame.shape[0]), True)
# Write the output frame to disk
writer.write(masked_frame)
# Release the file pointers
print("[INFO] cleaning up...")
writer.release()

成功执行脚本后,带有识别图像的视频文件将位于指定的路径中VIDEO_STREAM_OUT。我们使用一部电影运行我们的系统,并接收带有识别对象的视频文件。看看这里。

结论

在本文中,我们向您展示了我们如何利用Google Colab并解释了如何执行以下操作:

● 使用Google Colab提供的免费Tesla K80 GPU

● 使用Mask_RCNN神经网络和Google Colab对图像进行分类

● 使用Mask_RCNN,Google Colab和OpenCV库对视频流中的对象进行分类

欢迎评论并转发本文,关注@Ai技术联盟,会定期推送AI专业技术知识文章,有问题可以在下面留言,小编都会回复的,谢谢。

相关推荐

# Python 3 # Python 3字典Dictionary(1)

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如...

Python第八课:数据类型中的字典及其函数与方法

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值...

Python中字典详解(python 中字典)

字典是Python中使用键进行索引的重要数据结构。它们是无序的项序列(键值对),这意味着顺序不被保留。键是不可变的。与列表一样,字典的值可以保存异构数据,即整数、浮点、字符串、NaN、布尔值、列表、数...

Python3.9又更新了:dict内置新功能,正式版十月见面

机器之心报道参与:一鸣、JaminPython3.8的热乎劲还没过去,Python就又双叒叕要更新了。近日,3.9版本的第四个alpha版已经开源。从文档中,我们可以看到官方透露的对dic...

Python3 基本数据类型详解(python三种基本数据类型)

文章来源:加米谷大数据Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在Python中,变量就是变量,它没有类型,我们所说的"类型"是变...

一文掌握Python的字典(python字典用法大全)

字典是Python中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级Python开发...

超级完整|Python字典详解(python字典的方法或操作)

一、字典概述01字典的格式Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,...

Python3.9版本新特性:字典合并操作的详细解读

处于测试阶段的Python3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读、更紧凑的代码啦!Python版本你现在使用哪种版本的Python?3.7分?3.5分?还是2.7...

python 自学,字典3(一些例子)(python字典有哪些基本操作)

例子11;如何批量复制字典里的内容2;如何批量修改字典的内容3;如何批量修改字典里某些指定的内容...

Python3.9中的字典合并和更新,几乎影响了所有Python程序员

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

Python3大字典:《Python3自学速查手册.pdf》限时下载中

最近有人会想了,2022了,想学Python晚不晚,学习python有前途吗?IT行业行业薪资高,发展前景好,是很多求职群里严重的香饽饽,而要进入这个高薪行业,也不是那么轻而易举的,拿信工专业的大学生...

python学习——字典(python字典基本操作)

字典Python的字典数据类型是基于hash散列算法实现的,采用键值对(key:value)的形式,根据key的值计算value的地址,具有非常快的查取和插入速度。但它是无序的,包含的元素个数不限,值...

324页清华教授撰写【Python 3 菜鸟查询手册】火了,小白入门字典

如何入门学习python...

Python3.9中的字典合并和更新,了解一下

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

python3基础之字典(python中字典的基本操作)

字典和列表一样,也是python内置的一种数据结构。字典的结构如下图:列表用中括号[]把元素包起来,而字典是用大括号{}把元素包起来,只不过字典的每一个元素都包含键和值两部分。键和值是一一对应的...

取消回复欢迎 发表评论:

请填写验证码