在python中将字符串值拆分为整数

时间:2018-09-04 09:36:31

标签: python multidimensional-array split

我这里有一些不同的电话号码。每次都会改变。我需要创建一个多维数组,例如
array[x][y] => x应该通过在,之前分割来包含值,而y应该包含' '为空。
我怎样才能做到这一点 ?谢谢。

dat.xyz
2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9

output = open('dat.xyz', 'r') # See the r
output_list = output.read().strip().split(',')

我可以在,之前找到数字,但它仅显示一行。但是,我想做多维的。它应该拆分维度以查看为空的' '。谢谢。

输出应紧随其后

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

2 个答案:

答案 0 :(得分:6)

您应该首先在空格周围拆分以获取行,然后在这些行上进行迭代以获取单元格:

>>> rows = "2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9".split(' ')
>>> rows
['2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9']
>>> [row.split(',') for row in rows]
[['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9']]

您还可以将这些单元格转换为整数:

>>> [[int(cell) for cell in row.split(',')] for row in rows]
[[2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9]]

或让numpy为您完成转换:

>>> import numpy as np
>>> np.array([row.split(',') for row in rows], np.int)
array([[2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9]])

答案 1 :(得分:1)

import numpy as np

# read file and split over whitespace
with open('dat.xyz', 'r') as f:
    rows = f.read()
    rows = rows.split(' ')

arr = []

# split each value in row over comma, then convert each element to integer
for row in rows:
    row = row.split(',')
    for i in range(len(row)):
        row[i] = int(row[i])
    arr.append(row)

# convert to array
arr = np.array(arr)

arr

输出:

array([[2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9]])