【问题标题】:How to convert a python tuple of string to tuple of integer?如何将python字符串元组转换为整数元组?
【发布时间】:2019-03-07 07:11:19
【问题描述】:

我是 python 新手。谁能帮我解决这个问题?

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

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

到嵌套整数的元组:

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

提前致谢!

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

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!但是如果嵌套元组的数量未知呢?
【解决方案2】:

也许你需要一个递归函数。

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))

【讨论】:

  • 非常感谢!
【解决方案3】:

您可以使用带有小辅助函数的生成器表达式:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 2013-11-07
    • 2021-05-30
    • 1970-01-01
    • 2017-04-30
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多