列表的元素表示x和y十进制度坐标对,其中x和y坐标之间的空格格式为字符串:
'34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439', '35.298668 31.559237', '34.894127 29.761515
到目前为止,我可以选出第一个元素并将其设置为x值:
x = mystring[0:mystring.find(' ')]
如何迭代此字符串以生成一个由此字符串中的x和y坐标对组成的数组?
答案 0 :(得分:3)
mystring = mystring = "'34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439', '35.298668 31.559237', '34.894127 29.761515"
你可以得到一对像这样的对:
x = [pair.lstrip().strip("'").split(' ') for pair in mystring.split(',')]
# gives: [['34.894127', '29.761515'], ['32.323574', '30.166336'], ['32.677296', '31.961439'], ['35.298668', '31.559237'], ['34.894127', '29.761515']]
或者如果你真的想要元组:
x = tuple([tuple(pair.lstrip().strip("'").split(' ')) for pair in mystring.split(',')])
# gives: (('34.894127', '29.761515'), ('32.323574', '30.166336'), ('32.677296', '31.961439'), ('35.298668', '31.559237'), ('34.894127', '29.761515'))
答案 1 :(得分:3)
使用带有字符串作为输入的np.matrix
的快速方法:
如果
data
是一个字符串,则它被解释为带逗号或的矩阵 分隔列的空格和分隔行的分号。
string = ['34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439',
'35.298668 31.559237', '34.894127 29.761515']
np.matrix(';'.join(string))
#matrix([[ 34.894127, 29.761515],
# [ 32.323574, 30.166336],
# [ 32.677296, 31.961439],
# [ 35.298668, 31.559237],
# [ 34.894127, 29.761515]])
string = "'34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439', '35.298668 31.559237', '34.894127 29.761515"
np.matrix(string.replace(',', ';'))
#matrix([[ 34.894127, 29.761515],
# [ 32.323574, 30.166336],
# [ 32.677296, 31.961439],
# [ 35.298668, 31.559237],
# [ 34.894127, 29.761515]])
答案 2 :(得分:1)
您可以使用split(',')
获取每个字符串,然后split()
来获取坐标,例如使用list-comprehension:
mystring = "'34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439', '35.298668 31.559237', '34.894127 29.761515'"
coordinates = [tuple(map(float, x.replace("'", '').split())) for x in mystring.split(',')]
输出:
[(34.894127, 29.761515), (32.323574, 30.166336), (32.677296, 31.961439), (35.298668, 31.559237), (34.894127, 29.761515)]
答案 3 :(得分:1)
从字符串列表中获取numpy数组:
import numpy as np
string = ['34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439',
'35.298668 31.559237', '34.894127 29.761515']
s = np.array(list(map(lambda x: x.split(" "), string))).astype(float)
这导致s
[[ 34.894127 29.761515]
[ 32.323574 30.166336]
[ 32.677296 31.961439]
[ 35.298668 31.559237]
[ 34.894127 29.761515]]