简体   繁体   English

如何在Python列表列表中从字符串中生成数字列表

[英]How to make a list of numbers out of strings in a list of lists in Python

I have a list like this: 我有一个这样的清单:

[[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']],[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']]]

And I would like to get something like: 我想得到类似的东西:

[[[[0,1,2],[3,4,5]],[[5,6,7],[9,4,2]]],[[[0,1,2],[3,4,5]],[[5,6,7],[9,4,2]]]

I've tried string comprehension, the re module, splitting, stripping but none seem to work. 我尝试过字符串理解,re模块,拆分,剥离,但是似乎都没有用。 Thanks! 谢谢!

Recursion seems quite straightforward: 递归似乎很简单:

l = [[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']],[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']]]

def convert(x):
    if isinstance(x, list):
        return [convert(y) for y in x]
    else:
        return [int(y) for y in x.strip('()').split(',')]

convert(l) # [[[[0, 1, 2], [3, 4, 5]], [[5, 6, 7], [9, 4, 2]]], [[[0, 1, 2], [3, 4, 5]], [[5, 6, 7], [9, 4, 2]]]]

In case you want to see what it looks like in nested list comprehensions 如果您想查看嵌套列表推导中的外观

startList = [[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']],[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']]]
new = [[[[int(x) for x in moreSub.strip("()").split(",")] for moreSub in subitem] for subitem in item] for item in startList]
print(new)

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

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