在 Python 中从元组列表中删除所有字符串
在本文中,用户将了解如何在 Python 中从元组列表中删除所有字符串。在 Python 中使用元组列表时,通常会遇到希望删除元组中显示的任何字符串的情况。可以使用不同的方法从元组列表中删除字符串。在本文中,我们将研究三种不同的方法来完成此任务。这些方法包括使用列表推导、带有 lambda 函数的 filter() 方法以及带有元组卸载的 for 循环。
方法 1:使用列表推导
从元组列表中删除字符串的最简短和精致的方法之一是使用列表推导。列表推导的概念允许我们通过强调现有列表并应用条件来形成未使用的列表。
算法
步骤 1 − 定义一个名为 remove_strings_from_tuples() 的函数,该函数定义中包含一个参数。创建一个空列表来存储筛选后的元组。
步骤 2 - 重复唯一列表中的每个元组。
步骤 3 - 使用另一个重点检查元组中的每个元素。
步骤 4 - 在下一行中,如果元素不是字符串,则将其包含在已筛选元组中。
步骤 5 - 将已筛选元组添加到已筛选列表。
步骤 6 - 返回已筛选列表。
示例
# 创建用户定义函数
def remove_strings_from_tuples(tuples_list):
filtered_list = []
for tuple_item in tuples_list:
filtered_tuple = [element for element in tuple_item if not isinstance(element, str)]
filtered_list.append(tuple(filtered_tuple))
return filtered_list
#初始化元组列表
tuples_list = [(1, 'apple', 3.14), ('orange', 5, 'banana'), (7, 'grape', 'kiwi')]
result = remove_strings_from_tuples(tuples_list)
print(result)
输出
[(1, 3.14), (5,), (7,)]
方法 2:使用过滤器和 Lambda 函数
从元组列表中删除字符串的另一种方法是将 filter() 与 lambda 结合使用。 filter() 函数允许我们根据 lambda 函数指示的条件有针对性地包含或避免可迭代元素。
算法
步骤 1 - 创建一个名为 remove_strings_from_tuples() 的函数,该函数包含一个参数。
步骤 2 - 定义一个 lambda 函数,用于检查元素是否为字符串。
步骤 3 - 利用 filter() 方法将 lambda 函数应用于列表中的每个元组。
步骤 4 - 将结果转换回元组列表。
示例
#定义一个函数
def remove_strings_from_tuples(tuples_list):
filtered_list = list(filter(lambda t: not any(isinstance(element, str) for element in t), tuples_list))
return filtered_list
tuples_list = [(1, 'apple', 3.14), ('orange', 5, 'banana'), (7, 'grape', 'kiwi')]
#调用函数并将其值传递给结果变量
result = remove_strings_from_tuples(tuples_list)
print(result)
输出
[]
方法 3:使用 for 循环和元组解包
我们将要研究的最终方法包括使用 for 循环和元组卸载过程从元组中删除字符串。这种方法很明确,如果您喜欢更明确的编码方式,这种方法会很有用。
算法
步骤 1 - 创建名为 remove_strings_from_tuples() 的函数。创建一个空列表来存储元组。
步骤 2 - 使用 for 循环并重复唯一列表内的每个元组。
步骤 3 - 创建另一个列表来存储非字符串组件。
步骤 4 - 重复元组内的每个元素。
步骤 5 - 检查元素是否不是字符串,如果是,则将其添加到非字符串列表中。将非字符串列表改回元组。将元组添加到filtered_list。返回filtered_list。
示例
def remove_strings_from_tuples(tuples_list):
#创建一个空列表
filtered_list = []
#使用for循环遍历项目
for tuple_item in tuples_list:
non_string_elements = []
for element in tuple_item:
if not isinstance(element, str):
non_string_elements.append(element)
filtered_tuple = tuple(non_string_elements)
filtered_list.append(filtered_tuple)
return filtered_list
tuples_list = [(1, 'apple', 3.14), ('orange', 5, 'banana'), (7, 'grape', 'kiwi')]
result = remove_strings_from_tuples(tuples_list)
print(result)
输出
[(1, 3.14), (5,), (7,)]
结论
请记住考虑数据的特性和每种方法的执行建议。列表理解通常是最简短和有效的选择,但它可能不适用于非常广泛的记录。带有 lambda 函数的 filter() 函数提供了灵活性和意义,而带有元组卸载的 for 循环提供了更明确的编码风格。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

