📜  Python|从元组中删除字符串

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

Python|从元组中删除字符串

有时我们会遇到这样的问题:我们以元组的形式接收数据,我们只想要其中的数字并希望从中删除所有字符串。这在 Web 开发和机器学习中也很有用。让我们讨论可以实现这一特定任务的某些方法。

方法 #1:使用列表理解 + type()

上述 2 个功能的组合可用于解决此特定问题。列表推导式完成修改后的列表的重构任务,类型函数帮助我们过滤字符串。

# Python3 code to demonstrate
# Remove string from tuples
# using list comprehension + type()
  
# initializing list
test_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + type()
# Remove string from tuples
res = [tuple([j for j in i if type(j) != str])
                           for i in test_list]
  
# print result
print("The list after string removal is : " + str(res))
输出 :
The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]
The list after string removal is : [(1, 2), (4, ), (45, )]

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

这几乎是执行此特定任务的类似方法,但这里的更改只是使用 isinstance函数来检查字符串数据类型,其余的公式仍然基本相似。

# Python3 code to demonstrate
# Remove string from tuples
# using list comprehension + isinstance()
  
# initializing list
test_list = [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + isinstance()
# Remove string from tuples
res = [tuple(j for j in i if not isinstance(j, str))
                                 for i in test_list]
  
# print result
print("The list after string removal is : " + str(res))
输出 :
The original list : [('Geeks', 1, 2), ('for', 4, 'Geeks'), (45, 'good')]
The list after string removal is : [(1, 2), (4, ), (45, )]