"x"在Python语言中代表什么,特别是在"for"语句中?



我目前正在学习Python,开始被字母等的使用弄糊涂了。

tup = [1,2,3,4,5]
for t in tup:
print(t)

现在,我可以将"tup"更改为"mytuple"或"my_list_of_numbers"。我认为下一行是说"调用tup t,然后我们只打印t,而不是写打印tup",这是对的吗?

我很难理解在tup或mylist等中为X、T或Y写作的人之间的差异。

感谢您的帮助。

语法中的for在数据结构上创建迭代器。

所以当你使用:

for x in iterable_object : 
# Do something with x (ex : print(x))

x将取iterable_object中包含的每个值,因此在您的示例中是1,然后是2,然后是3,然后是4,然后是5。

此语法等效于:

for i in range(len(iterable_object)) : 
print(iterable_object[i])
# Do something with iterable_object[i]

这是一条捷径,就像句法糖。

For循环通过可迭代对象进行迭代。

代码块是为可迭代或序列的每个成员执行的。

实际语法为:

for variable in sequence:
# code

在Python中,For不需要索引变量序列化,只需在语句中声明即可。

在您的示例中,tup是您的可迭代对象,t是在迭代期间存储可迭代的当前元素的变量。

首先让我们考虑没有x、y或z,这里面什么都没有宇宙
你和我都只懂人类语言


现在让我们看看用纯英语编写的两个案例


情况1:现在如果我给你一包饼干,然后说:

open the packet and eat each buscuit one by one


情况2:然后再给你一包饼干,然后说:

for each buscuit in packet
eat it


结论:这两种情况在人类自然表达方面是相同的

现在让我们用Python语言说同样的单词


首先我们考虑有一个名为buscuit_packet的数组

buscuit-packet=[1,2,3,4,5,6,7,8,9,10]

由于蟒蛇不吃饼干,我们只需打印它们的

buscuit_packet = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for each in buscuit_packet:
print(each)

# here the word 'each' refers to one single buscuit we take and after using it
# we take the next one, it loops and the next one, it loops agian...
# until the last buscuit which is buscuit number 10 in our case and 
# alas after eating buscuit no. 10 the loop terminates
# ps. a human will probably eat(each)

此代码的输出为:

1
2
3
4
5
6
7
8
9
10

纯图像输出:
检查控制台输出的图像并感受代码

相关内容

最新更新