這樣的事情,使用itertools.cycle()。這適用於任何長度的字符串,第一部分,你可以決定的任何長度工作..(只是更換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'
拆開第一部分,由它構成一個循環。循環在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
爲了避免最後一個字符的末滴,你可以構建除了最後2部分的所有字符的列表(第2部分[: - 1]),然後添加的最後一個字符第2部分(第2部分[-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'
意外我在變量「公式」中添加了一個額外的'*' –
編輯您的帖子並將其刪除。 – IanAuld