Python|从字符串列表中删除第 K 个字符
有时,在处理数据时,我们可能会遇到需要删除特定列的问题,即字符串列表中的第 K 个字符。字符串是不可变的,因此删除只是意味着重新创建一个没有第 K 个字符的字符串。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表理解+列表切片
这是可用于执行此任务的简写。在此,我们只是使用切片重新创建所需的字符串,并使用列表推导将逻辑扩展到列表中的每个字符串元素。
# Python3 code to demonstrate working of
# Remove Kth character from strings list
# using list comprehension + list slicing
# initialize list
test_list = ['akash', 'nikhil', 'manjeet', 'akshat']
# printing original list
print("The original list : " + str(test_list))
# initialize K
K = 3
# Remove Kth character from strings list
# using list comprehension + list slicing
res = [ele[:K] + ele[K + 1:] for ele in test_list]
# printing result
print("List after removal of Kth character of each string : " + str(res))
输出 :
The original list : ['akash', 'nikhil', 'manjeet', 'akshat']
List after removal of Kth character of each string : ['akah', 'nikil', 'maneet', 'aksat']
方法 #2:使用map()
+ 切片
这个方法和上面的方法类似,唯一的区别是对list的每个元素的逻辑部分的扩展是借助map()来完成的。
# Python3 code to demonstrate working of
# Remove Kth character from strings list
# using list comprehension + list slicing
# initialize list
test_list = ['akash', 'nikhil', 'manjeet', 'akshat']
# printing original list
print("The original list : " + str(test_list))
# initialize K
K = 3
# Remove Kth character from strings list
# using list comprehension + list slicing
res = list(map(lambda ele: ele[ :K] + ele[K + 1 : ], test_list))
# printing result
print("List after removal of Kth character of each string : " + str(res))
输出 :
The original list : ['akash', 'nikhil', 'manjeet', 'akshat']
List after removal of Kth character of each string : ['akah', 'nikil', 'maneet', 'aksat']