移除 Python 元组中的字符串
当需要从元组中删除字符串时,可以使用列表解析和“type”方法。
列表可用于存储异构值(即任何数据类型的数据,如整数、浮点数、字符串等)。
元组列表基本上包含一个列表中都用元组括起来的元组。
列表解析是遍历列表并对其执行操作的速记。
“type”方法返回作为参数传递给它的可迭代类的类。
以下是相同的展示:
示例
my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]
print("The list is : ")
print(my_list)
my_result = [tuple([j for j in i if type(j) != str])
for i in my_list]
print("The list of tuple after removing the string is : ")
print(my_result)输出
The list is :
[('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]
The list of tuple after removing the string is :
[(45, 67), (45, 32), (59, 13)]解释
- 已定义一个元组列表,并将其显示在控制台上。
- 使用列表解析对其进行迭代。
- 将其检查为非字符串。
- 然后将其转换为元组,再转换为列表。
- 此操作的数据存储在变量中。
- 此变量是显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP