简体   繁体   English

如何获取元组列表并将元组从字符串更改为整数

[英]How to take a list of tuples and change the tuples from strings to integers

I have the code我有代码

l = [('1',['3','1','2']),('2',['4','5','2'])]

How do I make it:我该怎么做:

l = [(1,[3,1,2]),(2,[4,5,2])]

You can use int function while iterating using list comprehension您可以在使用列表理解进行迭代时使用int function

r = [tuple([int(i),[int(k) for k in j]]) for i,j in l]

This can be generalised using recursion:这可以使用递归来概括:

def to_ints(item):
    if isinstance(item, list):
        return [to_ints(e) for e in item]
    elif isinstance(item, tuple):
        return tuple(to_ints(e) for e in item)
    else:
        return int(item)

A simple approach is to remove the quotes and parse it back to a list一种简单的方法是删除引号并将其解析回列表

 l = eval(str(l).replace("'", ""))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM