Python切换元素的顺序

Rol*_*and 2 python

我是一个新手,正在寻找Python的禅宗:)今天的koan找到了解决以下问题的最Pythonesq方法:

成对地置换字符串的字母,例如

input:  'abcdefgh'
output: 'badcfehg'
Run Code Online (Sandbox Code Playgroud)

Ant*_*wns 13

我会去:

s="abcdefgh"
print "".join(b+a for a,b in zip(s[::2],s[1::2]))
Run Code Online (Sandbox Code Playgroud)

s [start:end:step]取每一步的字母,zip成对匹配它们,循环交换它们,连接给你一个字符串.


Joc*_*zel 6

我个人最喜欢做成对的事情:

def pairwise( iterable ):
   it = iter(iterable)
   return zip(it, it) # zipping the same iterator twice produces pairs

output = ''.join( b+a for a,b in pairwise(input))
Run Code Online (Sandbox Code Playgroud)

  • `n_tuples =(lambda iterable,n:zip(*[iter(iterable)]*n))` (2认同)

Lau*_*ves 5

''.join(s[i+1] + s[i] for i in range(0,len(s),2))
Run Code Online (Sandbox Code Playgroud)

是的,我知道使用范围不那么pythonic,但它很短,我可能没有必要解释它,以找出它的作用.

  • 如果你将它改为''.join(s [i] + s [i-1] for i in range(1,len(s),2))你可以避免奇数长度输入fwiw的异常. (2认同)