【问题标题】:Create a dictionary from values of a function, and using that for a graph从函数的值创建字典,并将其用于图形
【发布时间】:2017-01-08 21:24:29
【问题描述】:

我要做的是创建一个数学函数,它接受输入 n 并输出 a。我输入了一个更大的数字,它通过while loop,从该值中减去一个,打印a,并重复直到n 的某个值。我想要做的是将它放入字典中,n 作为键,a 作为值,并使用它通过matplotlib 绘制图形。 Looking around a bit there,它似乎不需要字典,只需要列表或数组,因此最好制作单独的键和值列表,然后输入,并更改标记等。这是我到目前为止的代码:

def intan(n=3):
    a = 180 -(360/n)
    while n >= 3:
        print(a)
        n -= 1
        intan(n)

intan(4)
    '''Returns strange output of 90.0, 60.0, 90.0,
    instead of just the first two'''

如您所见,代码中仍然存在一个稍微奇怪的错误,它多次循环输出输出,但经过一些修补后,我无法完全弄清楚这是为什么。谢谢各位!

更新:StephenRauch 的有用建议修复了奇怪的错误。

【问题讨论】:

  • 那么,您的问题是如何返回字典,如何在matplotlib 中绘制字典,或者为什么代码返回 90.0 两次?
  • 你混淆了递归和循环。您可能需要做其中之一。
  • a=...移动到while循环中并移除递归intan(n)调用。
  • 目标是为 n = 4 和 3 绘制180 -(360/n)
  • 循环是在循环中多次运行相同的代码,递归是调用相同的函数,然后从先前的调用返回到该函数,多次运行相同的代码。见en.wikipedia.org/wiki/Iteration#Computingen.wikipedia.org/wiki/Recursion_(computer_science)

标签: python python-3.x dictionary matplotlib


【解决方案1】:

我认为您想将函数从您正在处理的值中分离出来。如果 intan 应该只返回 180 -(360/n),则让它返回并在其他地方循环。

import matplotlib.pyplot as plt


def intan(n):
    return 180 -(360./n)

n_values = range(4, 100)
plt.plot(n_values, list(map(intan, n_values)))
plt.show()

等效的pandas 实现

import matplotlib.pyplot as plt
import pandas as pd


x = pd.Series(range(4, 100))
y = 180 - 360 / x

plt.plot(x, y)
plt.show()

【讨论】:

  • 啊哈,我喜欢这个解决方案,我似乎把它复杂化了。但是,当我运行它时,我得到:ValueError: x and y must have same first dimension.
  • 我为 Python 3 修复了它。
  • 非常感谢!我可以说用 PyPlot 搞得更多会很有趣! :)
  • 我建议您查看pandas。它使很多事情变得更容易——尤其是对齐数据。我添加了等效的 pandas 实现。
  • 我一定也会看看的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 2016-01-24
相关资源
最近更新 更多