简体   繁体   English

如何将 python 字符串转换为数组

[英]How to transform python string into array

a python string:一个 python 字符串:

'[[4,2],[8,5]]'

for example, where you have a fairly complex multidimensional array of information, maybe is extracted from a file or user input and is naturally a string.例如,如果您有一个相当复杂的多维信息数组,可能是从文件或用户输入中提取的,并且自然是一个字符串。 How should I go about turning this into an actual array.我应该如何 go 把它变成一个实际的数组。 I want a general implementation so that I can perform this to any multidimensional and complex array.我想要一个通用的实现,以便我可以对任何多维和复杂的数组执行此操作。 This is for a machine learning project, and any of these arrays can be represented with a shape (eg (3,2,5) ) and a list of its corresponding values (eg [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0] ) such that is may look like:这是一个机器学习项目,这些 arrays 中的任何一个都可以用一个形状(例如(3,2,5) )及其对应值的列表(例如[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0] )这样可能看起来像:

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

try this:尝试这个:

def flatten_list(_2d_list):
    flat_list = []
    for element in _2d_list:
        if type(element) is list:
            for item in element:
                flat_list.append(item)
        else:
            flat_list.append(element)
    return flat_list

nested_list = [[4,2],[8,5]]

print(nested_list)
print(flatten_list(nested_list))

import numpy as np
list = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
array = np.array(list)
array = np.reshape(array, (3,2,5))

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

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