要将一个列表中的str直接转为tuple,可以使用内置函数map()和tuple()。

首先,使用map()函数将列表中的每个元素都转为tuple。map()函数接收两个参数,第一个参数是一个函数,第二个参数是一个可迭代的对象(这里是列表)。函数可以是内置函数,也可以是自定义函数。在这里,我们将使用内置函数tuple()来将每个元素转为tuple。

然后,将map()函数的返回值转为一个新的tuple对象。可以使用tuple()函数来完成这一步。

以下是一个示例代码:

lst = ['hello', 'world', 'python']

# 使用map()函数将列表中的每个元素转为tuple
tuples = map(tuple, lst)

# 将map()函数的返回值转为一个新的tuple对象
result = tuple(tuples)

print(result)

输出结果:

(('h', 'e', 'l', 'l', 'o'), ('w', 'o', 'r', 'l', 'd'), ('p', 'y', 't', 'h', 'o', 'n'))

在这个示例中,列表['hello', 'world', 'python']中的每个元素都被转为了tuple对象,最终结果是一个包含了三个tuple的tuple对象。

如何将一个列表中的str直接转为tuple?

原文地址: http://www.cveoy.top/t/topic/hXC9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录