方法#1:使用列表理解+列表切片
這是可以用來完成此任務的簡寫。在此,我們只需使用切片重新創建所需的字符串,並使用列表推導擴展列表中字符串的每個元素的邏輯。
# Python3 代碼演示它是如何工作的
# 從字符串列表中刪除第 K 個字符
# 使用列表推導+ 列表切片
# 初始化列表
test_list
=
[
`akash`
,
`nikhil`
,
` manjeet `
,
`akshat`
]
# 打印原始列表
print
(
"原始列表:"
+
str
(test_list))
# 初始化K
K
=
3
# 從字符串列表中刪除第 K 個字符
# 使用列表推導 + 列表切片
res
=
[ele [: K]
+
ele [K
+
1
:]
for
ele
in
test_list]
# 打印結果
print
(
"去除每個字符串第K個字符後的列表:"
+
str
(res))
輸出:
原始列表:[`akash`,`nikhil`,`manjeet`,`akshat`] 去除每個字符串的第K個字符後的列表:[`akah `,`nikil`, `maneet`,`aksat`]
方法二:使用map()
+ slicing < br>這個方法和上面介紹的類似,唯一的區別是列表中每個元素的邏輯部分的展開都是使用map()來完成的。
# Python3 代碼來演示我如何t works
# 從字符串列表中刪除第 K 個字符
# 使用列表推導 + 切片列表
# 初始化列表
test_list = [ `akash` , `nikhil` , ` manjeet` , `akshat` ]
# 打印原始列表
print ( "原始列表:" + str (test_list ))
# 初始化 K
K = 3
# 刪除第K個字符列表行
# 使用列表理解 + 列表切片
res = list ( map ( lambda ele: ele [: K] + ele [K + 1 :], test_list))
# 聊天結果
print ( "去掉每個字符串第K個字符後的列表:" + str (res))
輸出: 原始列表:[`akash`,`nikhil`,`manjeet `,`akshat`] 刪除每個字符串的第 K 個字符後的列表:[`akah`,`nikil`,`maneet`,`aksat`]
Shop
Learn programming in R: courses $
Best Python online courses for 2022 $
Best laptop for Fortnite $
Best laptop for Excel $
Best laptop for Solidworks $
Best laptop for Roblox $
Best computer for crypto mining $
Best laptop for Sims 4 $
Latest questions
NUMPYNUMPY
psycopg2: insert multiple rows with one query
12 answers
NUMPYNUMPY
How to convert Nonetype to int or string?
12 answers
NUMPYNUMPY
How to specify multiple return types using type-hints
12 answers
NUMPYNUMPY
Javascript Error: IPython is not defined in JupyterLab
12 answers
Wiki
Python OpenCV | cv2.putText () method
numpy.arctan2 () in Python
Python | os.path.realpath () method
Python OpenCV | cv2.circle () method
Python OpenCV cv2.cvtColor () method
Python - Move item to the end of the list
time.perf_counter () function in Python
Check if one list is a subset of another in Python
Python os.path.join () method
|