我是一个新手,正在寻找Python的禅宗:)今天的koan找到了解决以下问题的最Pythonesq方法:
成对地置换字符串的字母,例如
Run Code Online (Sandbox Code Playgroud)input: 'abcdefgh' output: 'badcfehg'
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成对匹配它们,循环交换它们,连接给你一个字符串.
我个人最喜欢做成对的事情:
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)
''.join(s[i+1] + s[i] for i in range(0,len(s),2))
Run Code Online (Sandbox Code Playgroud)
是的,我知道使用范围不那么pythonic,但它很短,我可能没有必要解释它,以找出它的作用.
| 归档时间: |
|
| 查看次数: |
863 次 |
| 最近记录: |