将 Python 中的字符串列表转换成元组列表


使用 Python 操作数据时,我们可能会遇到包含字符串形式的数字的列表。此外,我们可能希望将字符串列表转换为元组。当然,给定的字符串是以特定的数字格式存在的。

使用 map 和 eval

我们将使用 map 函数对列表的每个元素应用 eval。然后将最终元素存储为一个列表。

示例

 实时演示

listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use eval
res = list(map(eval, listA))
# Result
print("List of tuples: \n",res)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

运行以上代码会给我们以下结果:−

Given list :
['21, 3', '13, 4', '15, 7']
List of tuples:
[(21, 3), (13, 4), (15, 7)]

使用 map 和 split

在此方法中,我们使用 split 函数,它会将带有逗号的元素分成两个不同的元素。接下来,我们应用元组函数来创建包含这些元素的元组,以对的形式存在。

示例

 实时演示

listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)

输出

运行以上代码会给我们以下结果:−

Given list :
['21, 3', '13, 4', '15, 7']
List of tuples:
[(21, 3), (13, 4), (15, 7)]

更新日期:2020 年 5 月 20 日

304 次浏览

开启你的 职业

完成课程可获得认证

开始学习
广告