Python中,append() 方法用於將一個對象添加到列表的末尾。如果這個對象本身是一個列表,那麽這個列表將作為一個整體(單個元素)被添加進去。
這里是一個簡單的例子來展示 extend() 和 append() 的區別:
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 0 19:08:01 2023
@author: SavingKing
"""
original_list = [1, 2, 3]
print("original_list:\n",original_list)
# 使用extend()
list_to_extend = [4, 5]
original_list.extend(list_to_extend)
# 结果: original_list = [1, 2, 3, 4, 5]
print("\noriginal_list after extend:\n",original_list)
# 使用append()
list_to_append = [6, 7]
original_list.append(list_to_append)
# 结果: original_list = [1, 2, 3, 4, 5, [6, 7]]
print("\noriginal_list after extend and append:\n",original_list)
輸出結果:
使用 extend() 方法時,list_to_extend 中的每個元素都被添加到 original_list 中。而使用 append() 方法時,list_to_append 被當作一個單獨的列表對象添加到 original_list 的末尾。
舉例:
lis_stop_commands = [
"systemctl stop httpd.service",
"systemctl stop mysqld.service",
"systemctl stop nginx.service",
"systemctl stop sshd.service",
"systemctl stop cups.service",
"systemctl stop docker.service"
]
lis_status_commands = \
[strr.replace("stop","status") for strr in lis_stop_commands]
lis_stop_commands 與
lis_status_commands
使用zip()成對地組合起來
這時候使用extend非常實用
INACTIVE = "Active: inactive (dead)"
lis_cmd_pairs=[]
for stop_cmd, status_cmd in zip(lis_stop_commands, lis_status_commands):
dic_status_cmd = {"command": status_cmd, "result": INACTIVE}
lis_cmd_pairs.extend([stop_cmd,dic_status_cmd])
systemctl stop
Linux的terminal沒有任何response
使用str type
systemctl status
terminal 會回應inactive (dead)
使用dict
或者如下coding:
INACTIVE = "Active: inactive (dead)"
lis_cmd_pairs=[]
for tup in zip(lis_stop_commands, lis_status_commands):
#dic_status_cmd = {"command": tup[1], "result": INACTIVE}
lis_cmd_pairs.extend(tup)
lis_cmd_pairs:
原本
stop類cmd一組
status類cmd另外一組
變成一次stop配一次相對應的status
推薦hahow線上學習python: https://igrape.net/30afN