【问题标题】:how to plot tuples on 2d list (python)如何在二维列表上绘制元组(python)
【发布时间】:2020-07-20 00:43:51
【问题描述】:

嗨,我正在尝试读取一个文本文件,该文件为我提供了我需要在二维列表上绘制的坐标。我的文本文件很简单,并且已经包含每行带有 x,y 的图。这是它看起来包含的内容:

3,2

3,3

3,4

4,4

4,5

4,6

到目前为止,我已经能够从文件中提取坐标,但我不知道如何绘制元组。这是我的代码:

fnhandle = open(file_name)  
    lines = fnhandle.readlines()
    lines = [item.rstrip("\n") for item in lines]
    r_c_coordinates = list()
    for item in lines:
            item = item.split(",")
            item = tuple(int(items) for items in item)
            r_c_coordinates.append(item)                
    fnhandle.close()

编辑:“情节”是指我有一个包含 0 的初始化二维列表。我必须回到元组坐标处的二维列表并将它们更改为 1

【问题讨论】:

  • 你的意思是,像在二维图上一样绘制?
  • 看看matplotlib——你可以绘制多种风格的图表。它确实有一些僵硬的初始学习曲线,但它会做你需要的。
  • 不幸的是,我们在二维列表/数组上进行了分配。使用matplot等会被扣分

标签: python python-3.x tuples


【解决方案1】:

如果“绘图”是指在 2D 图形上,这可能是最简单的方法:

import matplotlib.pyplot as plt
x_coords = [coord[0] for coord in r_c_coordinates]
y_coords = [coord[1] for coord in r_c_coordinates]
plt.plot(x_coords, y_coords, "k.", lw=0)

【讨论】:

    【解决方案2】:

    “情节”是指我有一个包含 0 的初始化二维列表。 我必须回到元组坐标处的二维列表和 将这些更改为 1

    在内存中的网格中绘制点的示例:

    file_name = "points.txt"
    
    my_grid = [[0] * 10 for _ in range(10)]  # 10 by 10 grid of zeros
    
    def print_grid(grid):
        for row in grid:
            print(*row)
    
    print_grid(my_grid)
    
    r_c_coordinates = list()
    
    with open(file_name) as file:
        for line in file:
            coordinate = [int(n) for n in line.rstrip().split(',')]
            r_c_coordinates.append(tuple(coordinate))
    
    for row, column in r_c_coordinates:
        my_grid[column][row] = 1
    
    print('- ' * len(my_grid[0]))
    print_grid(my_grid)
    

    我假设从零开始的坐标。

    输出(带注释)

    > python3 test.py
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    - - - - - - - - - - 
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 1 0 0 0 0 0 0  # 3,2
    0 0 0 1 0 0 0 0 0 0  # 3,3
    0 0 0 1 1 0 0 0 0 0  # 3,4 & 4,4
    0 0 0 0 1 0 0 0 0 0  # 4,5
    0 0 0 0 1 0 0 0 0 0  # 4,6
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    >
    

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多