如果列表中不包含任何字符,请从 Python 元组列表中移除元组


当需要根据给定条件从元组列表中移除一个元组时,即元组不包含特定字符,可以使用列表解析。

可以使用列表来存储异构值(即任何数据类型的数据,如整数、浮点数、字符串等)。元组列表基本上包含一些包含在列表中的元组。

列表解析是遍历列表并执行其上操作的一种简写。

以下是同一演示:

示例

实时演示

my_list = [('. ', 62), ('Mark', 5),
   ('Paul.', 21), ('.....', 0),
   ('-Jane', 115), ('Jake', 15),
   ('::', 63), ('John', 3), ('--', 1),
   ('there', 82), ('Harold', 100)]

my_result = [(a, b) for a, b in my_list
   if any(c.isalpha() for c in a)]

print("The tuple that doesn't contain any character has been removed")
print("The resultant list of tuple is :")
print(my_result)

输出

The tuple that doesn't contain any character has been removed
The resultant list of tuple is :
[('Mark', 5), ('Paul.', 21), ('-Jane', 115), ('Jake', 15), ('John', 3), ('there', 82), ('Harold', 100)]

说明

  • 定义了一个元组列表,并在控制台上显示。
  • 该元组列表被遍历,并检查它是否属于字母族。
  • 此操作的数据存储在一个变量中。
  • 此变量是显示在控制台上的输出。

更新日期:2021-03-13

372 个浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.