鱼C论坛

 找回密码
 立即注册
查看: 1163|回复: 3

[已解决]老版本列表打印的问题

[复制链接]
发表于 2019-7-18 17:50:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
例9.1 使用列表
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
--------------------------------------------------------------------------------
这个是书中的例子,因为是讲的2.X版本的,所以
这段:
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
实际似乎hi相当于3.X的:
print( 'These items are:',
for item in shoplist:
print item)
但是我实际操作的时候
>>> a
[1, 3, 5, 6, 7, 7, 8, 67, 923, 'wi', 'dags', 'agasg']
>>> print('these element are',
          for i in a:
          
SyntaxError: invalid syntax
第一个问题:这里就直接语法错误了,是因为版本原因不能把for循环放print()里面吗?还是我自己不会用?

第二个问题:我自己又想了个办法,定义了个函数:
>>> def buy(a):
          for i in a:
                  print(i)

          
>>> print('these element are',buy(a))
          
1
3
5
6
7
7
8
67
923
wi
dags
agasg
these element are None
结果打印出来的结果很像是系统在运行的时候,先运行了buy()函数,再运行了print()的感觉,请问
$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
要达成书中这样的输出,应该怎么弄?

最佳答案
2019-7-18 18:03:05
把python2的程序改为3的可以这样操作。
  1. shoplist = ['apple', 'mango', 'carrot', 'banana']
  2. print('I have', len(shoplist),'items to purchase.')
  3. print('These items are:', end = ' ')
  4. for item in shoplist:
  5.     print(item, end = ' ')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-7-18 18:03:05 | 显示全部楼层    本楼为最佳答案   
把python2的程序改为3的可以这样操作。
  1. shoplist = ['apple', 'mango', 'carrot', 'banana']
  2. print('I have', len(shoplist),'items to purchase.')
  3. print('These items are:', end = ' ')
  4. for item in shoplist:
  5.     print(item, end = ' ')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-7-18 18:16:19 | 显示全部楼层
冬雪雪冬 发表于 2019-7-18 18:03
把python2的程序改为3的可以这样操作。

明白了,等于把第三行代码后面无缝接上for 的内容是吗?谢谢:)

关于第二个问题能说下吗?
>>> print('these element are',buy(a))
          
1
3
5
6
7
7
8
67
923
wi
dags
agasg
these element are None
这部分的输出,好像是先运行了我def的buy()函数,完了之后才开始运行print(),这个是怎么回事?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-7-18 20:01:34 | 显示全部楼层
livermore1877 发表于 2019-7-18 18:16
明白了,等于把第三行代码后面无缝接上for 的内容是吗?谢谢:)

关于第二个问题能说下吗?

是的,函数就是先运算它的参数,比如print(3+5)得到的结果就是8
运算器参数这里就是执行buy(a),即逐个打印列表的元素。然后再打印'these element are'和buy(a)的返回值None
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-26 03:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表