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

问个问题 'abcdefghigklmnopqrstuvwxyz'怎么切成 ['abc','def','ghi'…]这样的形式啊

  •  
  •   whnzy · 2016-04-17 20:08:17 +08:00 · 5286 次点击
    这是一个创建于 2902 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如题!
    29 条回复    2016-04-23 12:25:56 +08:00
    SErHo
        2
    SErHo  
       2016-04-17 20:14:01 +08:00   ❤️ 4
    ["abcdefghigklmnopqrstuvwxyz"[i: i+3] for i in range(0, len("abcdefghigklmnopqrstuvwxyz"), 3)]
    aec4d
        3
    aec4d  
       2016-04-17 20:48:10 +08:00   ❤️ 1
    re.findall('.{3}','abcdefghigklmnopqrstuvwxyz')
    billion
        4
    billion  
       2016-04-17 20:51:16 +08:00
    2 楼正解。
    hcwhan
        5
    hcwhan  
       2016-04-17 20:53:27 +08:00 via Android
    2 楼这样 如果不是 3 的倍数会报索引超出 错误吧
    wittyfox
        6
    wittyfox  
       2016-04-17 21:20:35 +08:00 via Android
    str = ('a'..'z').to_a.join
    # => "abcdefghijklmnopqrstuvwxyz"

    str.split('').each_slice(3).to_a.map(&:join)
    => ["abc",
    "def",
    "ghi",
    "jkl",
    "mno",
    "pqr",
    "stu",
    "vwx",
    "yz"]
    wittyfox
        7
    wittyfox  
       2016-04-17 21:26:22 +08:00 via Android
    如果核心库更完善的话,像这样:

    ```ruby
    String.class_eval do
    include Enumerable
    alias :each :each_char
    end
    ```

    那就可以这样:

    ```ruby
    str.each_slice(3).to_a
    ```
    dant
        8
    dant  
       2016-04-17 21:28:58 +08:00
    @wittyfox 然而这里是 Python 版(
    seki
        9
    seki  
       2016-04-17 21:34:12 +08:00
    @hcwhan 不会
    sjtlqy
        10
    sjtlqy  
       2016-04-17 21:36:56 +08:00
    xuboying
        11
    xuboying  
       2016-04-17 21:44:16 +08:00
    能用正则就用正则啊
    #!python
    import re
    x="abcdefghijklmnopqrstuvwxyz"
    print re.findall(r".{1,3}",x)
    xcodebuild
        12
    xcodebuild  
       2016-04-17 21:46:21 +08:00
    JavaScript 版:

    'abcdefghigklmnopqrstuvwxyz'.match(/.{3}/g) // => ["abc", "def", "ghi", "gkl", "mno", "pqr", "stu", "vwx"]
    ty0716
        13
    ty0716  
       2016-04-17 21:54:11 +08:00
    >>> import textwrap
    >>> end.join(textwrap.wrap(body, chunklen))

    https://docs.python.org/2/library/textwrap.html
    SakuraSa
        14
    SakuraSa  
       2016-04-17 22:04:47 +08:00
    以前用过一个奇怪的方法实现:

    ```python
    s,n='abcdefghigklmnopqrstuvwxyz',3
    g=iter(s)
    print([''.join(i) for i in zip(*[g]*n)])
    ```

    >>> ['abc', 'def', 'ghi', 'gkl', 'mno', 'pqr', 'stu', 'vwx']


    要保留最后的 yz 的话,可以:

    ```python
    import itertools
    s,n='abcdefghigklmnopqrstuvwxyz',3
    g=iter(s)
    print([''.join(j for j in i if j) for i in itertools.izip_longest(*[g]*n)])
    ```

    >>>['abc', 'def', 'ghi', 'gkl', 'mno', 'pqr', 'stu', 'vwx', 'yz']
    leavic
        15
    leavic  
       2016-04-17 22:22:06 +08:00
    from more_itertools import chunked


    搞定了
    msg7086
        16
    msg7086  
       2016-04-17 23:54:52 +08:00 via Android
    @wittyfox 就知道有人会贴 ruby 版 w
    araraloren
        17
    araraloren  
       2016-04-18 10:58:58 +08:00
    ~~ perl6 版

    ```perl6
    #!/usr/bin/env perl6


    # 3 个一组合
    say (comb /\w ** 3/, ['a' ... 'z'].join);

    # 输出 (abc def ghi jkl mno pqr stu vwx)


    # 保留 yz
    say (comb /\w ** 3 | \w ** 2/, ['a' ... 'z'].join);

    # 输出 (abc def ghi jkl mno pqr stu vwx yz)
    ```
    liyj144
        18
    liyj144  
       2016-04-18 13:43:52 +08:00
    参考 2 楼,加上末尾的处理: re.findall('.{3}|.{2}$','abcdefghigklmnopqrstuvwxyz')
    liyj144
        19
    liyj144  
       2016-04-18 13:45:02 +08:00
    @liyj144 刚写错了,是三楼
    HustLiu
        20
    HustLiu  
       2016-04-18 14:32:13 +08:00
    @codefalling 可以优化一下 /.{1,3}/g ,这样避免字符串长度不是 3 的倍数出现遗漏
    jackal
        21
    jackal  
       2016-04-18 18:11:06 +08:00
    Javascript+正则表达式版本
    <script type="text/javascript">
    var str = "abcdefghigklmnopqrstuvwxyz";
    var exp = /[a-z]{3}/g;
    var arr = [];
    var index = 0;

    while ((arr = exp.exec(str)) !== null) {
    console.log(arr[0]);
    index = exp.lastIndex;
    }
    console.log(str.substring(index));
    </script>
    irenicus
        22
    irenicus  
       2016-04-18 20:20:29 +08:00 via Android
    perl 版
    @out = ("abcdef" =~ /(...)/);
    irenicus
        23
    irenicus  
       2016-04-18 20:23:49 +08:00 via Android
    那个不行
    @out = split /(...)/, "abcdefghijklmnopqrstuvwxyz";
    不是三的倍数也行
    xcodebuild
        24
    xcodebuild  
       2016-04-18 21:03:06 +08:00
    @HustLiu 有道理
    extreme
        25
    extreme  
       2016-04-18 22:00:07 +08:00
    C 版:
    int x = 0, y = 0;
    char *string ="abcdefghigklmnopqrstuvwxyz" , three_char[9][4] = {0};
    while (*string != '\0') {
    three_char[x][y % 3] = *string;
    y++;
    if (y == 3) {
    y = 0;
    x++;
    }
    string++;
    }
    saxon
        26
    saxon  
       2016-04-19 08:56:44 +08:00
    s = "abcdefghijklmnopqrstuvwxyz"
    print zip(s[::3]+s[1::3]+s[2::3])
    :)
    saxon
        27
    saxon  
       2016-04-19 09:03:24 +08:00
    更正,刚手滑回车
    s = "abcdefghijklmnopqrstuvwxyz"
    def func(s):
    l = list(s)
    return ''.join(l)
    print map(func,zip(s[::3],s[1::3],s[2::3]))
    dofine
        28
    dofine  
       2016-04-20 00:31:19 +08:00 via iPad
    def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
    whnzy
        29
    whnzy  
    OP
       2016-04-23 12:25:56 +08:00
    我想是不是应该再来点 C++,Golang,C#,OC,erlang,Java,Haskell.........
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1042 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:36 · PVG 06:36 · LAX 15:36 · JFK 18:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.