如何将字符串的python元组转换为整数元组?

时间:2019-03-07 07:11:19

标签: python python-3.x

我是python的新手。有人可以帮我解决这个问题吗?

我想用一个未知数量的嵌套元组转换一个嵌套字符串元组,例如:

(('1','2'), ('3','4'), ('5','6'), ... ('100','101'))

到嵌套整数元组:

((1,2), (3,4), (5,6), ... (100,101))

谢谢!

编辑:添加了“如果嵌套元组的数量未知,该怎么办?”

3 个答案:

答案 0 :(得分:2)

使用map()将字符串值映射为整数:

tupl = (('1','2'), ('3','4'))

print(tuple(tuple(map(int, x)) for x in tupl))
# ((1, 2), (3, 4))

答案 1 :(得分:1)

也许您需要递归函数。

def get_int_tuple(rows):
    result = []
    for row in rows:
        if isinstance(row, tuple):
            if all(map(lambda s: isinstance(s, str) and s.isdigit(), row)):
                result.append(tuple(map(int, row)))
            else:
                result.extend(get_int_tuple(row))
    return tuple(result)


tupl = (('1', '2'), ('3', '4'), ('5', '6'))

arr = get_int_tuple(tupl)
print(arr)

tupl = ((('1', '2'), ('3', '4')), ('5', '6'))

arr = get_int_tuple(tupl)
print(arr)

结果:

((1, 2), (3, 4), (5, 6))
((1, 2), (3, 4), (5, 6))

答案 2 :(得分:0)

您可以将生成器表达式与一个小的辅助函数一起使用:

t = (('1','2'), ('3','4'), ('5','6'))

func = lambda x: tuple(int(i) for i in x)

tuple(func(i) for i in t)
# ((1, 2), (3, 4), (5, 6))