python交换字符对的位置,并反转2个字符

2024-10-06 12:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,但不完整。我来解释一下过程。你知道吗

我有话要说。你知道吗

abcdefgh

现在我将这个单词配对成两个字符。你知道吗

ab cd ef gh

然后每两对呼气一次

cd ab gh ef

下一步我将反转字符对。你知道吗

dc ba hg fe

如果单词的长度是偶数,而成对或字符也是偶数,就会发生这种情况。你知道吗

如果这对单词是奇数,长度也是奇数呢。你知道吗

例如:abcdefghi

这将是。。ab cd ef gh i

如果单词的长度是奇数。我给最后一对加一个衬垫。"x"

ab cd ef gh ix

然后像以前一样做同样的过程。但这对角色也很奇怪。因此,最后一对将保留其位置。你知道吗

cd ab gh ef ix

然后反转字符

dc ba hg fe xi

现在我可以添加填充并为每个单词配对。我仍在考虑如何交换他们的立场和扭转字符。你知道吗

这是我的密码。你知道吗

def is_odd(num):
   return num % 2 != 0

IMSI = "5150201234567"

count = len(str(IMSI))

if (is_odd(count) is True):
    IMSI = str(IMSI)+"f"


count = len(str(IMSI)) 


x = 0
z = []


while x <= count-2:
    a = x
    x = x + 2
    b = x
    z.append(IMSI[a:b][::-1])

print z
# output is ['15', '05', '02', '21', '43', '65', 'f7']

Tags: abis过程countcddchg字符
2条回答

没什么特别的。所有基本操作。你知道吗

s = 'abcdefgh'
# s = 'abcdefghi'

# pad
if len(s) % 2:
    s += 'x'

l = []
# split
for i in range(0,len(s),2):
    l.append(s[i:i+2])

# switch
for i in range(0,len(l),2):
    if i+1 < len(l):
        l[i+1], l[i] = l[i:i+2]

# reverse each
l = [x[::-1] for x in l]

print l

使用itertoolsfuncy的函数方法:

from funcy import ichunks
from itertools import chain


s = "abcdefghi"

if len(s) % 2:
    s += "x"

xs = [x[::-1] for x in chain(*[x[::-1] for x in ichunks(2, ichunks(2, s))])]

相关问题 更多 >