像这样,使用itertools.cycle()。这将适用于任何长度的字符串和您可以决定的任何长度的 part1 ..(只需将 2 替换为变量)
In [35]: from itertools import cycle
In [36]: s='*+123'
In [37]: part1=cycle(s[:2])
In [38]: part2=s[2:]
In [39]: processed_string=''.join([digit+part1.next() for digit in part2])[:-1]
In [40]: processed_string
Out[40]: '1*2+3'
拆开第一部分,从中制作一个循环。cycle 在 next() 上保持循环迭代。
列表推导构造了 part2 中每个数字的列表,并与 itertools.cycle 上的 next() 连接起来,称为 part1(这使得它在 * 和 + 之间交替)。
''.join() 这个列表来做一个字符串。去掉尾随的额外内容,因为最后一次迭代不需要它。
解释
In [50]: part1=cycle(s[:2])
In [51]: part1.next()
Out[51]: '*'
In [52]: part1.next()
Out[52]: '+'
In [53]: part1.next()
Out[53]: '*'
In [54]: part1.next()
Out[54]: '+'
In [55]: #alternates
In [56]: # list comp
In [57]: [digit for digit in part2]
Out[57]: ['1', '2', '3']
In [58]: [digit+part1.next() for digit in part2]
Out[58]: ['1*', '2+', '3*']
In [59]: # this is a list of strings and can be joined using join.
In [60]: ''.join([digit+part1.next() for digit in part2])
Out[60]: '1+2*3+'
In [61]: # this has a trailing extra character. get rid of it using slices
In [62]: ''.join([digit+part1.next() for digit in part2])[:-1]
Out[62]: '1*2+3'
In [63]: #solution
为避免最后一个字符的丢失,您可以为除 last(part2[:-1]) 之外的 part2 的所有字符构造列表,然后添加 part2(part2[-1]) 的最后一个字符,如下所示:
In [64]: part1=cycle(s[:2])
In [65]: ''.join([digit+part1.next() for digit in part2[:-1]])
Out[65]: '1*2+'
In [66]: ''.join([digit+part1.next() for digit in part2[:-1]])+part2[-1]
Out[66]: '1*2+3'
您可以将它包含在这样的函数中:
In [67]: # enclose in a function
In [68]: def process_text(text,no_of_symbols):
....: part1=cycle(text[:no_of_symbols])
....: part2=text[no_of_symbols:]
....: return ''.join([digit+part1.next() for digit in part2])[:-1]
....:
In [69]: process_text('+*-123456',3)
Out[69]: '1+2*3-4+5*6'