简体   繁体   English

将元组列表列表转换为列表列表列表

[英]Converting list of lists of tuples to list of lists of lists

I have this old random list:我有这个旧的随机列表:

old_list = [[(0, 1), (0, 2)], [(8, 4), (3, 7)]]

And I want to convert the tuples to lists like this:我想将元组转换为这样的列表:

>>> new_list = [[[0, 1], [0, 2]], [[8, 4], [3, 7]]]

I tried the below with a list comprehension, but apparently, it is wrong:我用列表理解尝试了以下内容,但显然这是错误的:

new_list = [list (y for y in x) for x in old_list]

You need nested list comprehensions to create a nested result.您需要嵌套列表推导来创建嵌套结果。 The tuples that need to be converted to lists are at the second level down.需要转换为列表的元组位于第二层。

new_list = [[list(tup) for tup in level1] for level1 in old_list]

You can do this:你可以这样做:

new_list = [[list(x) for x in y] for y in old_list]

which produces:产生:

[[[0, 1], [0, 2]], [[8, 4], [3, 7]]]

That's what you do:)这就是你所做的:)
list(np.array(old_list)

You can convert to array with numpy module or you can simply just convert to list with list() method.您可以使用 numpy 模块转换为数组,也可以简单地使用 list() 方法转换为列表。 Look for example:例如:

Code Example代码示例

This is the basic solution and there is no user of the extra list.这是基本解决方案,没有额外列表的用户。 I am updating the old_list:我正在更新 old_list:

for i in range(0, len(old_list)):
    for j in range(0, len(old_list[i])):
        old_list[i][j] = list(old_list[i][j])
print old_list

O/P输出/输出

[[[0, 1], [0, 2]], [[8, 4], [3, 7]]]

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

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