Joining pairs of elements of a list

后端 未结 6 2033
独厮守ぢ
独厮守ぢ 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: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

提交回复
热议问题