Voronoi未绘制实时数据元组索引超出范围

问题描述 投票:-1回答:1

我正在尝试绘制具有实时数据的voronoi图,但出现错误:

IndexError: tuple index out of range

代码:

data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes

data = str(data, "utf-8") #convert bytes into string and fix the 'b'
#data.decode("utf-8", errors="ignore")

data = data.strip(" ").split(".")

x = data[0]
y = data[1]
x = float(x.replace( ',', '.'))
y = float(y.replace( ',', '.'))
vor = Voronoi(x,y)

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9oaEdhby5wbmcifQ==” alt =“代码和错误”>

data变量的值是这样的:[b' 0,2036377.2,04291.', b' 0,2027879.2,040747.']

任何想法如何解决此问题?

python tuples voronoi index-error
1个回答
0
投票

如评论中所述,收到的错误是因为您将错误的输入传递给Voronoi,请阅读documentation

关于您要做什么,并假设您从data获得的data, addr = sock.recvfrom(1024)像这样[b' 0,2036377.2,04291.', b' 0,2027879.2,040747.'],那么您必须解决以下几点:

  • 将字节解码为字符串
  • 例如使用正则表达式提取坐标
  • 将坐标的字符串表示形式转换为float
  • 组织数据结构以创建Voronoi

到目前为止,您拥有的代码已解决了大多数这些问题,但它并未将数据构成为Voronoi图的输入。

下面的代码解决了所有问题,并将为您创建Voronoi图:

import re
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
import doctest
doctest.testmod()  # used to test the docstring 

# compile the regular expression used to parse the input data
regex = re.compile(' (\d+,\d+)\.(\d+,\d+)\.')

def parse_data(data):
    """
    parse a list of strings with x, y coordinates

    >>> data = [b' 0,2036377.2,04291.', b' 0,2027879.2,040747.']
    >>> parse_data(data)
    [[0.2036377, 2.04291], [0.2027879, 2.040747]]
    """
    proc_data = []
    for i in data:
        m = regex.match(i.decode('utf-8')) # decode the bytes and match the regex
        if m:
            # parse the coordinates and organise the data structure
            proc_data += [[float(m.group(1).replace(',','.')),
                           float(m.group(2).replace(',','.'))]]
    return proc_data

data = [b' 0,2036377.2,04291.', b' 0,2027879.2,040747.', 
        b' 0,2018921.2,037455.', b' 0,2010467.2,034439.', 
        b' 0,2004007.2,031721.', b' 0,1996321.2,027795.',
        b' 0,1989551.2,023898.', b' 0,1983429.2,020666.',
        b' 0,1978466.2,017263.']

data = parse_data(data)
vor = Voronoi(data)  # create the Voronoi diagram with correct input data
voronoi_plot_2d(vor)
plt.show()

结果如下:“

© www.soinside.com 2019 - 2024. All rights reserved.