Python新手求助一个for循环的问题

空山悟 2014-12-15 03:33:51
这段代码是输出两个元祖的合并结果:

albums = ('1', '2', '3', '4')
years = ('0', '0', '0', '0')

for yr in zip(albums, years):
print yr

显示结果:

这里很清楚意思。

然后我不懂的是下面的这段:

albums = ('1', '2', '3', '4')
years = ('0', '0', '0', '0')

for album, yr in zip(albums, years):
print yr, album

显示结果:


为何输出结果为如下?yr从zip的结果里取数据的,那么album从哪里取数据的呢?
...全文
311 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
空山悟 2015-01-03
  • 打赏
  • 举报
回复
引用 6 楼 u010680933 的回复:
楼主不明白的应该是为什么print一个字符串,出来的结果没有带引号 你可以在Python命令行中试下:
a='das'
a
print a
print的结果的确是不带引号的 因为Python中一切都是对象,print函数实际上是调用了对象的__str__()方法
object.__str__(self) 
Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

猜测原因应该是在这,所谓的informal指的就是我们日常生活使用的字符串形式,因此不带引号
这几天很忙没上 非常感谢你的回答 已结贴。!
JPF1024 2014-12-23
  • 打赏
  • 举报
回复
效果一样的,思路不同而已的
sprawling 2014-12-19
  • 打赏
  • 举报
回复
这个解释的很明白,谢谢。
尽量坚持 2014-12-17
  • 打赏
  • 举报
回复
楼主不明白的应该是为什么print一个字符串,出来的结果没有带引号 你可以在Python命令行中试下:
a='das'
a
print a
print的结果的确是不带引号的 因为Python中一切都是对象,print函数实际上是调用了对象的__str__()方法
object.__str__(self) 
Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

猜测原因应该是在这,所谓的informal指的就是我们日常生活使用的字符串形式,因此不带引号
bugs2k 2014-12-16
  • 打赏
  • 举报
回复
print [yr, album]
空山悟 2014-12-16
  • 打赏
  • 举报
回复
引用 1 楼 bugs2k 的回复:
非常感谢你的回答 再请问下,为何pack的结果输出是整型,而不是字符串型呢? 结果是: 0 1 0 2 为何不是 '0' '1' '0' '2' 呢? 我方才测试了以下: u = '1' print u 这段代码的输出结果为 1,请问为何不是 '1' 呢?
-柚子皮- 2014-12-16
  • 打赏
  • 举报
回复
for yr in zip(albums, years): #zip返回的是一个列表(其中的每个元素是元组) print yr yr的类型是元组 输出(albums0, years0) (albums1, years1) ... for album, yr in zip(albums, years): print yr, album yr,album等价于(yr,album)合起来才是元组 输出( years0,albums0) (years1,albums1) ... 楼主明白否?
woods2001 2014-12-15
  • 打赏
  • 举报
回复
for yr in zip(albums, years): 其中yr就是一个元组,在这里就是你看到(1,0),也就是后面的album,yr的取值来源
bugs2k 2014-12-15
  • 打赏
  • 举报
回复

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧