Joining pairs of elements of a list

后端 未结 6 2019
独厮守ぢ
独厮守ぢ 2020-11-27 11:32

I know that a list can be joined to make one long string as in:

x = [\'a\', \'b\', \'c\', \'d\']
print \'\'.join(x)

Obviously this would ou

相关标签:
6条回答
  • 2020-11-27 12:05

    Use an iterator.

    List comprehension:

    >>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
    >>> [c+next(si, '') for c in si]
    ['abcde', 'fghijklmn', 'opqr']
    
    • Very efficient for memory usage.
    • Exactly one traversal of s

    Generator expression:

    >>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
    >>> pair_iter = (c+next(si, '') for c in si)
    >>> pair_iter # can be used in a for loop
    <generator object at 0x4ccaa8>
    >>> list(pair_iter) 
    ['abcde', 'fghijklmn', 'opqr']
    
    • use as an iterator

    Using map, str.__add__, iter

    >>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
    >>> map(str.__add__, si, si)
    ['abcde', 'fghijklmn', 'opqr']
    

    next(iterator[, default]) is available starting in Python 2.6

    0 讨论(0)
  • 2020-11-27 12:11

    just to be pythonic :-)

    >>> x = ['a1sd','23df','aaa','ccc','rrrr', 'ssss', 'e', '']
    >>> [x[i] + x[i+1] for i in range(0,len(x),2)]
    ['a1sd23df', 'aaaccc', 'rrrrssss', 'e']
    

    in case the you want to be alarmed if the list length is odd you can try:

    [x[i] + x[i+1] if not len(x) %2 else 'odd index' for i in range(0,len(x),2)]
    

    Best of Luck

    0 讨论(0)
  • 2020-11-27 12:12
    >>> lst =  ['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'] 
    >>> print [lst[2*i]+lst[2*i+1] for i in range(len(lst)/2)]
    ['abcde', 'fghijklmn', 'opqr']
    
    0 讨论(0)
  • 2020-11-27 12:18

    Well I would do it this way as I am no good with Regs..

    CODE

    t = '1. eat, food\n\
    7am\n\
    2. brush, teeth\n\
    8am\n\
    3. crack, eggs\n\
    1pm'.splitlines()
    
    print [i+j for i,j in zip(t[::2],t[1::2])]
    

    output:

    ['1. eat, food   7am', '2. brush, teeth   8am', '3. crack, eggs   1pm']  
    

    Hope this helps :)

    0 讨论(0)
  • 2020-11-27 12:22

    Without building temporary lists:

    >>> import itertools
    >>> s = 'abcdefgh'
    >>> si = iter(s)
    >>> [''.join(each) for each in itertools.izip(si, si)]
    ['ab', 'cd', 'ef', 'gh']
    

    or:

    >>> import itertools
    >>> s = 'abcdefgh'
    >>> si = iter(s)
    >>> map(''.join, itertools.izip(si, si))
    ['ab', 'cd', 'ef', 'gh']
    
    0 讨论(0)
  • 2020-11-27 12:29

    You can use slice notation with steps:

    >>> x = "abcdefghijklm"
    >>> x[0::2] #0. 2. 4...
    'acegikm'
    >>> x[1::2] #1. 3. 5 ..
    'bdfhjl'
    >>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
    ['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
    

    Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.

    0 讨论(0)
提交回复
热议问题