整数数组的字符串列表

时间:2018-10-22 18:48:12

标签: python arrays python-3.x numpy

从这样的字符串列表中:

example_list = ['010','101']

我需要获取一个整数数组,其中每一行都是字符串中的每一个,是一列中的每个字符,就像这样:

example_array = np.array([[0,1,0],[1,0,1]])

我已经尝试过使用此代码,但是它不起作用:

example_array = np.empty([2,3],dtype=int)    
i = 0 ; j = 0

for string in example_list:
    for bit in string:
        example_array[i,j] = int(bit)
        j+=1
    i+=1

有人可以帮助我吗?我正在使用Python 3.6。

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

如果所有字符串的长度都相同(这对于构建连续数组至关重要),请使用view有效地分隔字符。

r = np.array(example_list)
r = r.view('<U1').reshape(*r.shape, -1).astype(int)

print(r)
array([[0, 1, 0],
       [1, 0, 1]])

您还可以使用列表理解路线。

r = np.array([[*map(int, list(l))] for l in example_list])

print(r)
array([[0, 1, 0],
       [1, 0, 1]])

答案 1 :(得分:1)

最简单的方法是使用列表理解,因为它会自动为您生成输出列表,可以轻松将其转换为numpy数组。您可以使用多个for循环来执行此操作,但是您将无法创建列表,子列表并追加到它们。虽然不难,但代码具有列表理解功能,看起来更优雅。

尝试一下:

newList = np.array([[int(b) for b in a] for a in example_list])

newList现在看起来像这样:

>>> newList
 ... [[0, 1, 0], [1, 0, 1]]

注意:尽管确实可以,但此时无需调用map。

那么这是怎么回事?我们逐项遍历您的原始字符串列表(example_list),然后遍历当前项中的每个字符。从功能上讲,这相当于...

newList = []

for a in example_list:
    tmpList = []
    for b in a:
        tmpList.append(int(b))
    newList.append(tmpList)

newList = np.array(newList)

我个人认为,对于初学者来说,多个for循环更容易理解。但是,一旦掌握了列表的理解力,您可能就不想再回头了。

答案 2 :(得分:0)

您可以使用map进行此操作:

example_array = map(lambda x: map(lambda y: int(y), list(x)), example_list)

外部lambdalist(x)中的每个项目执行example_list操作。例如,'010' => ['0','1','0']。内部的lambda将各个字符(来自list(x)的结果)转换为整数。例如,['0','1','0'] => [0,1,0]

相关问题