如何使用matplotlib.pyplot一次性绘制列表?

时间:2017-02-12 20:59:56

标签: python python-2.7 matplotlib

我创建了一个计算素数的程序。这只是一个测试,但我认为在图表上绘制它会很有趣。

import matplotlib.pyplot as plt

max = int(input("What is your max no?: "))
primeList = []

for x in range(2, max + 1):
  isPrime = True
  for y in range (2 , int(x ** 0.5) + 1):
     if x % y == 0:
        isPrime = False
        break

     if isPrime:
        primeList.append(x)


print(primeList)

如何绘制primeList,我可以在for循环之外一次完成吗?

1 个答案:

答案 0 :(得分:1)

这将列出您的列表与其索引:

from matplotlib import pyplot as plt

plt.plot(primeList, 'o')
plt.show()

这个程序:

from matplotlib import pyplot as plt

max_= 100
primeList = []

for x in range(2, max_ + 1):
    isPrime = True
    for y in range (2, int(x ** 0.5) + 1):
        if x % y == 0:
            isPrime = False
            break
    if isPrime:
        primeList.append(x)

plt.plot(primeList, 'o')
plt.show()

得出这个情节:

enter image description here

相关问题