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
scylla
V2EX  ›  Python

请教 PY 的两个循环结束添加元素到集合,结果为什么不一样?

  •  
  •   scylla · 2015-01-24 22:57:46 +08:00 · 2656 次点击
    这是一个创建于 3351 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码要实现的功能是把文本文件里的IP地址匹配出来,并把IP添加到集合里。

    代码1:

    <script src=".py">

    re_ip = re.compile('[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}')
    ip_list = []
    with open(path, 'r') as f:
    for line in f:
    ips = re_ip.findall(line)
    ip_list.append(str(x) for x in ips)

    </script>

    代码1里,集合的结果是这种对象 <generator object <genexpr> at 0x10417ffa0> .... 其实我想要的是IP地址。


    代码2:

    <script src=".py">

    re_ip = re.compile('[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}')
    ip_list = []
    with open(path, 'r') as f:
    for line in f:
    ips = re_ip.findall(line)
    for x in ips:
    ip_list.append(x)

    </script>

    代码2的集合里,结果才是IP地址。

    为什么会这样?请不吝赐教,谢谢。
    6 条回复    2015-01-26 01:45:40 +08:00
    SakuraSa
        1
    SakuraSa  
       2015-01-24 23:01:21 +08:00
    因为 ip_list.append(str(x) for x in ips) 中的 (str(x) for x in ips) 就是一个 generator 呀
    我觉得你可能是想这样 ip_list.extend(str(x) for x in ips)
    SakuraSa
        2
    SakuraSa  
       2015-01-24 23:02:54 +08:00
    另外 findall 的结果就是一个字符串的数组
    可以直接 ip_list.append(re_ip.findall(line))
    SakuraSa
        3
    SakuraSa  
       2015-01-24 23:03:19 +08:00
    错了,是 ip_list.extend(re_ip.findall(line))
    huangyanan
        4
    huangyanan  
       2015-01-24 23:05:02 +08:00
    extend for the first sample
    scylla
        5
    scylla  
    OP
       2015-01-24 23:08:59 +08:00
    @SakuraSa

    谢谢。 (str(x) for x in ips) 会被解释成一个 generator?怪不得。 ip_list.extend(re_ip.findall(line)) 是可用的。

    话说怎么粘代码高亮?用markdown 的’‘’python 和<script src=".py"> 标签都不行。
    ryd994
        6
    ryd994  
       2015-01-26 01:45:40 +08:00 via Android
    写程序时不看文档么?出了问题还不看?
    既然看见存了genenrator,那就看看哪个list方法会取出所有元素而不是直接存入集合啊!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4054 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:14 · PVG 18:14 · LAX 03:14 · JFK 06:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.