📌  相关文章
📜  Python – 从元组的第一个元素中删除给定的字符

📅  最后修改于: 2022-05-13 01:55:41.014000             🧑  作者: Mango

Python – 从元组的第一个元素中删除给定的字符

给定一个元组列表,从元组的第一个元素中删除 K 个字符。

方法 #1:使用 replace() + 列表推导

在此,我们使用 replace() 执行删除 K字符的任务,并使用列表理解来改造元组。

Python3
# Python3 code to demonstrate working of 
# Remove K character from first element of Tuple
# Using replace() + list comprehension
  
# initializing list
test_list = [("GF ! g !", 5), ("! i ! s", 4), ("best !!", 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = "!"
  
# replace with empty string removes the desired char.
res = [(sub[0].replace(K, ''), sub[1]) for sub in test_list]
  
# printing result 
print("The filtered tuples : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove K character from first element of Tuple
# Using translate() + list comprehension
  
# initializing list
test_list = [("GF ! g !", 5), ("! i ! s", 4), ("best !!", 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = "!"
  
# translation after conversion to ascii number 
res = [(sub[0].translate({ord(K): None}), sub[1]) for sub in test_list]
  
# printing result 
print("The filtered tuples : " + str(res))


输出
The original list is : [('GF!g!', 5), ('!i!s', 4), ('best!!', 10)]
The filtered tuples : [('GFg', 5), ('is', 4), ('best', 10)]

方法 #2:使用 translate() + 列表理解

在此,我们使用 translate() 执行删除任务,需要使用 ord() 转换为 ascii,并替换为空字符。

Python3

# Python3 code to demonstrate working of 
# Remove K character from first element of Tuple
# Using translate() + list comprehension
  
# initializing list
test_list = [("GF ! g !", 5), ("! i ! s", 4), ("best !!", 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = "!"
  
# translation after conversion to ascii number 
res = [(sub[0].translate({ord(K): None}), sub[1]) for sub in test_list]
  
# printing result 
print("The filtered tuples : " + str(res))
输出
The original list is : [('GF!g!', 5), ('!i!s', 4), ('best!!', 10)]
The filtered tuples : [('GFg', 5), ('is', 4), ('best', 10)]