【问题标题】:How to convert a multi-dimensional array containing multiple arrays of tuples to lists in python?如何将包含多个元组数组的多维数组转换为python中的列表?
【发布时间】:2020-04-18 11:23:52
【问题描述】:

我正在使用下面的函数来转换一个由多个数组组成的多维数组,这些数组里面有元组。结果应该类似于desired_result。

sample_md_array = [[(99, 'string_1'), (45, 'string_2')], [(15, 'string_3'), (48, 'string_4')]]

def convert(md_array):
    new_array = []
    for array in md_array:
        for tup in array:
            new_array.append(list(tup))

    return new_array

result_using_convert_function = [[99, 'string_1'], [45, 'string_2'], [15, 'string_3'], [48, 'string_4']]

desired_result = [[[99, 'string_1'], [45, 'string_2']], [[15, 'string_3'], [48, 'string_4']]]

【问题讨论】:

    标签: python-3.x list tuples


    【解决方案1】:

    您可以通过列表推导将元组转换为列表:

    >>> sample_tuple = [[(99, 'string_1'), (45, 'string_2')], [(15, 'string_3'), (48, 'string_4')]]
    >>> [[list(y) for y in x] for x in sample_tuple]
    [[[99, 'string_1'], [45, 'string_2']], [[15, 'string_3'], [48, 'string_4']]]
    

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 1970-01-01
      • 2012-04-04
      • 2015-12-30
      • 1970-01-01
      • 2020-03-24
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多