V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yyy32
V2EX  ›  Python

Python 学习中的问题

  •  
  •   yyy32 · 2017-02-25 22:00:46 +08:00 · 1834 次点击
    这是一个创建于 2588 天前的主题,其中的信息可能已经有所发展或是发生改变。

    def count():

    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs
    

    f1, f2, f3 = count()

    这个代码中 为什么单独运行 f1=count ()会报错呢 typeerror

    还有就是为什么 f1 , f2=count () 也会报错 valueerror

    为什么这 2 个报错还不一样呢

    9 条回复    2017-02-26 18:32:58 +08:00
    forrestchang
        1
    forrestchang  
       2017-02-26 06:49:02 +08:00
    语法并没有错误,在 Python 3.5 中没有报错。

    ryd994
        2
    ryd994  
       2017-02-26 07:00:33 +08:00 via Android
    f1, f2=count() 这个很好理解
    正常来说 f1-3 三个变量,返回值是 3 函数的 list
    正好一一对应
    现在你只给两个变量,对应不上
    yyy32
        3
    yyy32  
    OP
       2017-02-26 09:16:05 +08:00
    @forrestchang 我是在 python2.7 上运行这个的 单独运行 f1=count ()就报错了
    staticor
        4
    staticor  
       2017-02-26 10:18:10 +08:00
    记得在 Python Cookbook 第一章第一节就是讲的这个例子, 函数返回多值的 Unpacking 问题.

    f1, f2 = .... 这样表示左侧是一个 tuple 要对应于右侧也是一个 tuple/或可转换的结构, 而且长度要求为 2, 否则报 ValueError



    若执行 f1=count() 我这里测试也没问题, 结果用 f1[1] f1[2] 访问,
    系统版本是 2.7 (sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0))
    cyrbuzz
        5
    cyrbuzz  
       2017-02-26 10:21:22 +08:00
    1. 2.7.11 测试不报错。
    2. 三个列表是不能平均分给两个变量的。
    3. 在循环里重复创建同样的函数真的好吗。。
    zsz
        6
    zsz  
       2017-02-26 10:32:43 +08:00 via iPhone
    @yyy32 可以加我们的群问,这样效率更高,这个群是一群工程师组建的面向初学者的 python Linux 学习群, qq 群号: 278529278 ,非商业性质,拒绝广告,只接收真正想学这方面技术的朋友,交流学习,申请请说明来自 v2ex
    forrestchang
        7
    forrestchang  
       2017-02-26 12:22:10 +08:00
    @yyy32 错误提示能给一下吗?
    yyy32
        8
    yyy32  
    OP
       2017-02-26 18:07:16 +08:00
    @forrestchang typeerror :‘ list ’ object is not callalbe
    kaneg
        9
    kaneg  
       2017-02-26 18:32:58 +08:00
    我怀疑楼主不是用 f1=count(), 而是 f1=count()()
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1112 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:49 · PVG 06:49 · LAX 15:49 · JFK 18:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.