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

Python 相关问题

  •  
  •   MrgHOST · 2017-09-11 18:28:59 +08:00 · 2512 次点击
    这是一个创建于 2423 天前的主题,其中的信息可能已经有所发展或是发生改变。

    ‘ 7w876543217w'怎么拆分成[7w,87,65,43,21,7w]

    list['7w876543217w']貌似不行

    12 条回复    2017-09-13 00:41:14 +08:00
    Cooky
        1
    Cooky  
       2017-09-11 18:35:33 +08:00 via Android
    [ list[i,I+2] for i in range(len(list)) ]
    Cooky
        2
    Cooky  
       2017-09-11 18:36:08 +08:00 via Android   ❤️ 1
    @Cooky 第一个逗号改冒号,切片
    MrgHOST
        3
    MrgHOST  
    OP
       2017-09-11 18:37:03 +08:00
    @Cooky 谢谢
    qlbr
        4
    qlbr  
       2017-09-11 18:37:46 +08:00   ❤️ 1
    >>> import re
    >>> string='7w876543217w'
    >>> re.findall('.{2}',string)
    ['7w', '87', '65', '43', '21', '7w']
    Cooky
        5
    Cooky  
       2017-09-11 18:41:17 +08:00 via Android   ❤️ 1
    @MrgHOST 直接用 str 切片就行,转 list 多余了…
    nauynah
        6
    nauynah  
       2017-09-11 20:10:54 +08:00 via iPhone   ❤️ 2
    >>> [str[i: i+2] for i in range(0, 10, 2)]
    acheapskate
        7
    acheapskate  
       2017-09-11 20:11:19 +08:00   ❤️ 1
    s = '7w876543217w'
    l = [m + n for m,n in zip(s[0::2],s[1::2])]
    acheapskate
        8
    acheapskate  
       2017-09-11 20:19:32 +08:00
    @nauynah range(0, 11, 2) ,不然截取不到最后 2 个字符 。感觉用 range 分隔还是最明晰方便的
    nauynah
        9
    nauynah  
       2017-09-11 20:35:59 +08:00
    @acheapskate 是的,我把字符串长度看成 10 了
    40huo
        10
    40huo  
       2017-09-11 21:30:47 +08:00   ❤️ 1
    [string[x : x + width] for x in range(0, len(string), width)]
    yucongo
        11
    yucongo  
       2017-09-13 00:32:28 +08:00
    In [538]: [elm + s[1::2][idx] for idx, elm in enumerate(s[::2])]
    Out[538]: ['7w', '87', '65', '43', '21', '7w']
    yucongo
        12
    yucongo  
       2017-09-13 00:41:14 +08:00
    In [544]: s
    Out[544]: '7w876543217w'

    In [545]: [ s[2*idx: 2*idx+2] for idx in range(len(s)//2)]
    Out[545]: ['7w', '87', '65', '43', '21', '7w']
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   799 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:50 · PVG 04:50 · LAX 13:50 · JFK 16:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.