从函数的值创建字典,并将其用于图形

2024-03-29 14:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的是做一个数学函数,它接受输入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'''

正如您所看到的,代码仍然有一个稍微奇怪的错误,它多次循环输出,但是经过一些修补之后,我不太明白这是为什么。谢谢你们

更新:stephernauch的建议修正了这个奇怪的错误


Tags: of函数代码loop字典matplotlib错误bit
1条回答
网友
1楼 · 发布于 2024-03-29 14:19:55

我想你应该把函数从你要处理的值中分离出来。如果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()

enter image description here

相关问题 更多 >