推荐学习书目
› 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 · Apr 17, 2016 · 6887 views
    This topic created in 3851 days ago, the information mentioned may be changed or developed.
    如题!
    29 replies  •  2016-04-23 12:25:56 +08:00
    SErHo
    SErHo
    Apr 17, 2016❤️4
    2
    ["abcdefghigklmnopqrstuvwxyz"[i: i+3] for i in range(0, len("abcdefghigklmnopqrstuvwxyz"), 3)]
    aec4d
    aec4d
    Apr 17, 2016❤️1
    3
    re.findall('.{3}','abcdefghigklmnopqrstuvwxyz')
    billion
    billion
    Apr 17, 2016
    4
    2 楼正解。
    hcwhan
    hcwhan
    Apr 17, 2016 via Android
    5
    2 楼这样 如果不是 3 的倍数会报索引超出 错误吧
    wittyfox
    wittyfox
    Apr 17, 2016 via Android
    6
    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
    wittyfox
    Apr 17, 2016 via Android
    7
    如果核心库更完善的话,像这样:

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

    那就可以这样:

    ```ruby
    str.each_slice(3).to_a
    ```
    dant
    dant
    Apr 17, 2016
    8
    @wittyfox 然而这里是 Python 版(
    seki
    seki
    Apr 17, 2016
    9
    @hcwhan 不会
    xuboying
    xuboying
    Apr 17, 2016
    11
    能用正则就用正则啊
    #!python
    import re
    x="abcdefghijklmnopqrstuvwxyz"
    print re.findall(r".{1,3}",x)
    xcodebuild
    xcodebuild
    Apr 17, 2016
    12
    JavaScript 版:

    'abcdefghigklmnopqrstuvwxyz'.match(/.{3}/g) // => ["abc", "def", "ghi", "gkl", "mno", "pqr", "stu", "vwx"]
    chac88
    chac88
    Apr 17, 2016
    13
    >>> import textwrap
    >>> end.join(textwrap.wrap(body, chunklen))

    https://docs.python.org/2/library/textwrap.html
    SakuraSa
    SakuraSa
    Apr 17, 2016
    14
    以前用过一个奇怪的方法实现:

    ```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
    leavic
    Apr 17, 2016
    15
    from more_itertools import chunked


    搞定了
    msg7086
    msg7086
    Apr 17, 2016 via Android
    16
    @wittyfox 就知道有人会贴 ruby 版 w
    araraloren
    araraloren
    Apr 18, 2016
    17
    ~~ 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
    liyj144
    Apr 18, 2016
    18
    参考 2 楼,加上末尾的处理: re.findall('.{3}|.{2}$','abcdefghigklmnopqrstuvwxyz')
    liyj144
    liyj144
    Apr 18, 2016
    19
    @liyj144 刚写错了,是三楼
    HustLiu
    HustLiu
    Apr 18, 2016
    20
    @codefalling 可以优化一下 /.{1,3}/g ,这样避免字符串长度不是 3 的倍数出现遗漏
    jackal
    jackal
    Apr 18, 2016
    21
    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
    irenicus
    Apr 18, 2016 via Android
    22
    perl 版
    @out = ("abcdef" =~ /(...)/);
    irenicus
    irenicus
    Apr 18, 2016 via Android
    23
    那个不行
    @out = split /(...)/, "abcdefghijklmnopqrstuvwxyz";
    不是三的倍数也行
    xcodebuild
    xcodebuild
    Apr 18, 2016
    24
    @HustLiu 有道理
    extreme
    extreme
    Apr 18, 2016
    25
    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
    saxon
    Apr 19, 2016
    26
    s = "abcdefghijklmnopqrstuvwxyz"
    print zip(s[::3]+s[1::3]+s[2::3])
    :)
    saxon
    saxon
    Apr 19, 2016
    27
    更正,刚手滑回车
    s = "abcdefghijklmnopqrstuvwxyz"
    def func(s):
    l = list(s)
    return ''.join(l)
    print map(func,zip(s[::3],s[1::3],s[2::3]))
    dofine
    dofine
    Apr 20, 2016 via iPad
    28
    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
    whnzy
    OP
    Apr 23, 2016
    29
    我想是不是应该再来点 C++,Golang,C#,OC,erlang,Java,Haskell.........
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2991 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 10:52 · PVG 18:52 · LAX 02:52 · JFK 05:52
    ♥ Do have faith in what you're doing.