[英]How to make a list of numbers out of strings in a list of lists in Python
我有一個這樣的清單:
[[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']],[['(0,1,2)','(3,4,5)'],['(5,6,7)','(9,4,2)']]]
我想得到類似的東西:
[[[[0,1,2],[3,4,5]],[[5,6,7],[9,4,2]]],[[[0,1,2],[3,4,5]],[[5,6,7],[9,4,2]]]
我嘗試過字符串理解,re模塊,拆分,剝離,但是似乎都沒有用。 謝謝!
遞歸似乎很簡單:
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]]]]
如果您想查看嵌套列表推導中的外觀
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.