我正在从 Coursera 学习 python。我写了一个程序,根据当我点击屏幕时,它画一个圆圈。请参阅下面的程序--
# Dots
# importing
import simplegui
import math
width = 600
height = 600
ball_list = []
radius = 20
colour = "Yellow"
# position ditector
def distance(p,q) :
return math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)
# Mouse click -- Change the position
def click(pos) :
ball_list.append(pos)
# global position
# global colour
# if distance(pos, position) < radius :
# colour = "Blue"
# else :
# position = list(pos)
# colour = "Yellow"
# Drawing the ball
def draw(canvas) :
for position in ball_list :
canvas.draw_circle(position , radius , 2, "Black" , colour)
# Creating the frame
frame = simplegui.create_frame("Dots" , 600,600)
frame.set_canvas_background("White")
frame.set_draw_handler(draw)
# mouse click
frame.set_mouseclick_handler(click)
# Start
frame.start()
但我的疑问是在 def draw(canvas) 中,
for position in ball_list
,我没有定义任何位置。我做了 position = list(pos)
作为评论。那么 position in ball_list
中的位置值是多少,没有值的 for 循环如何工作?什么是迭代? for 循环和迭代有什么区别?
如果上述代码在您的 IDE 中无法运行,请访问 http://www.codeskulptor.org/#user38_VSZ0jZ0uTh_0.py 并运行它。
for
循环有点不同。我将尝试用您编写的代码进行解释。每次调用 click
函数时,您都会将 pos
附加到名为 ball_list
的列表中,您需要绘制圆圈。
def click(pos) :
ball_list.append(pos) ## appends the pos to ball_list
现在,在使用
pos
列出列表后,您可以调用以下函数。
def draw(canvas) :
for position in ball_list :
canvas.draw_circle(position , radius , 2, "Black" , colour)
这里变量
position
从第一个值到最后一个值迭代您已附加到列表 pos
的所有 ball_list
。
如果您想知道 position
变量的值如何以及是什么,请打印它的值并亲自查看,如下所示:
def draw(canvas) :
for position in ball_list :
print position ## prints one pos value in the ball_list for each iteration.
canvas.draw_circle(position , radius , 2, "Black" , colour)
a_list = [1, 2, 3, 4, 5, 6, 7]
for x in [10, 20, 30, 40, 50]:
print x
10 20 30 40 50
for x in a_list:
print x
1 2 3 4 5 6 7
for i in range(10):
print i
1 2 3 4 5 6 7 8 9 10
假设您有自己的类,并且希望它是可迭代的:
class MyRange(object):
def __init__(self, low, high):
self.low = low
self.high = high
def __iter__(self):
low = self.low
while self.high >= low:
yield low
low += 1
现在您可以:
r = MyRange(1, 10)
for number in r:
print number,
number
现在在每次迭代中都有从 __iter__
返回的值。这就是 Python 中的工作方式,在您的例子中,您有一个 list
,它有自己的 __iter__
并以类似的方式使用。
在Python中,
for x in y:
迭代y
中的每一项,并将当前迭代的值赋给变量x
,以便您可以在for循环体内引用该值。 这里有一个 eval.in 可以帮助您了解它是如何工作的。
这里与 Java 进行一个简单的比较,假设变量“arrayList”是一个
ArrayList
(Java) 或 list
(Python) 的事物,并且您想要对列表中的每个值调用方法 do_something_with()
。
Python:
for x in arrayList:
do_something_with(x)
Java:
for (int i = 0; i < arrayList.size(); i++) {
do_something_with(arrayList.get(i));
}
从根本上来说,你可以编写看起来更像 Java 的 Python:
for x in range(0, len(arrayList)):
do_something_with(arrayList[x])
这段代码会做同样的事情。然而,Python 意识到这是一个足够常见的任务,为其提供一定程度的抽象是有价值的(在编程语言中通常称为“语法糖”)。您可以在 python 文档中阅读有关 Python 迭代器以及如何迭代不同类型的数据的更多信息。
最低分数 = 0
student_scores 中的分数:
if score <= score:
lowest_score = score
打印(最低分数)