繁体   English   中英

在 Python 中将一系列数字转换为数组

[英]Convert series of numbers to array in Python

我想在不使用任何库的情况下将一系列数字转换为 Python 中的数组。 ( 0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8) (1,3 3,4 5,9 7,5 10,2 11, 4 20,10 ) (0,0 6,6 12,3 19,6 (green)) 例如这三个系列。 如果没有像 numpy 这样的库,是否可以做到这一点? 我尝试使用 numpy 但并为第一个系列找到了这样的解决方案。

array([[ 0,  2],
       [ 3,  0],
       [ 4,  5],
       [ 7,  8],
       [ 8,  6],
       [ 9,  5],
       [13,  6],
       [15,  9],
       [17, 10],
       [21,  8]])

但教授不接受这一点。

如果

a = "1,2 2,3 3,4 ..."

然后

result = [map(int, v.split(",")) for v in a.split()]

会给你

print result
[[1, 2], [2, 3], [3, 4], ... ]

如果数字系列是字符串行,那么您可以尝试下一个代码:

a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"

lines = a.split(' ')
arr = [[int(i) for i in x.split(',')] for x in lines]
print arr

输出

[[0, 2], [3, 0], [4, 5], [7, 8], [8, 6], [9, 5], [13, 6], [15, 9], [17, 10], [21, 8]]

编辑(避免 O(n^2))

一种方式通过:

a = "0,2 3,0 4,5 7,8 8,6 9,5 13,6 15,9 17,10 21,8"    
position = 0
previous_position = 0
final_array = []
temp_array = []
for character in a:
    if character == ',':
        temp_array = []
        temp_array.append(int(a[previous_position:position]))
        previous_position = position
    elif character == ' ':
        temp_array.append(int(a[previous_position+1:position]))
        previous_position = position+1
        final_array.append(temp_array)
    elif position == len(a) - 1:
        temp_array.append(int(a[previous_position+1:]))
        final_array.append(temp_array)

    position += 1

print final_array

暂无
暂无

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

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