简体   繁体   English

Python切换元素的顺序

[英]Python switch order of elements

I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem: 我是一个新手,正在寻找Python的禅宗:)今天的koan找到了解决以下问题的最Pythonesq方法:

Permute the letters of a string pairwise, eg 成对地置换字符串的字母,例如

 input: 'abcdefgh' output: 'badcfehg' 

I'd go for: 我会去:

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

s[start:end:step] takes every step'th letter, zip matches them up pairwise, the loop swaps them, and the join gives you back a string. s [start:end:step]取每一步的字母,zip成对匹配它们,循环交换它们,连接给你一个字符串。

my personal favorite to do stuff pairwise: 我个人最喜欢做成对的事情:

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))
''.join(s[i+1] + s[i] for i in range(0,len(s),2))

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

I just noticed that none of the existing answers work if the length of the input is odd. 我只注意到没有一个现有的答案工作,如果输入的长度为奇数。 Most of the answers lose the last character. 大多数答案都失去了最后一个字符。 My previous answer throws an exception. 我之前的回答引发了异常。

If you just want the last character tacked onto the end, you could do something like this: 如果你只想将最后一个字符添加到最后,你可以这样做:

print "".join(map(lambda a,b:(b or '')+a, s[::2], s[1::2]))

or in 2.6 and later: 或者在2.6及更高版本中:

print "".join(b+a for a,b in izip_longest(s[::2],s[1::2], fillvalue=''))

This is based on Anthony Towns's answer, but uses either map or izip_longest to make sure the last character in an odd-length string doesn't get discarded. 这是基于Anthony Towns的答案,但是使用mapizip_longest来确保奇数长度字符串中的最后一个字符不被丢弃。 The (b or '') bit in the map version is to convert the None that map pads with into '' . (b or '')中的位map版本到转换Nonemap与成垫''

Since in Python, every string is also an iterable, itertools comes in handy here. 因为在Python中,每个字符串也是可迭代的,所以itertools在这里派上用场。

In addition to the functions itertools provides, the documentation also supplies lots of recipes. 除了itertools提供的功能外,文档还提供了大量的配方。

from itertools import izip_longest

# From Python 2.6 docs
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Now you can use grouper to group the string by pairs, then reverse the pairs, then join them back into a string. 现在你可以使用石斑鱼对成对的字符串进行分组,然后反转它们,然后将它们连接成一个字符串。

pairs = grouper(2, "abcdefgh")
reversed_pairs = [''.join(reversed(item)) for item in pairs]
print ''.join(reversed_pairs)

This may look a little scary, but I think you'd learn a lot deciphering the following idiom: 这可能看起来有点可怕,但我认为你已经学到了很多解读以下习语:

s = "abcdefgh"
print ''.join(b+a for a,b in zip(*[iter(s)]*2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM