首页 > 解决方案 > 将字符串列表转换为 2 元组整数列表

问题描述

我目前有以下列表:['10 90', '10 -90', '100 45', '20 180']。我正在尝试将字符串列表转换为充满整数的 2 元组,例如[(10, 90), (10, -90), (100, 45), (20, 180)].

我试过使用这段代码:

res = [tuple(map(int, sub.split(', '))) for sub in test_list]

但是,我收到此错误:

ValueError: invalid literal for int() with base 10: '10 90'
Command exited with non-zero status 1 

任何帮助将不胜感激。

标签: pythonlisttuples

解决方案


尝试这个:

lst = ['10 90', '10 -90', '100 45', '20 180']
res = [tuple(map(int, x.split())) for x in lst]
print(res)

输出:

[(10, 90), (10, -90), (100, 45), (20, 180)]

推荐阅读