2014-03-25 76 views
1

例如:使用python中環兩個字符串轉換成一個字符串

裂傷( '你好', '人') - > 'hpeelolpole'

它是爲了結合這兩個字符串,逐字符。 這是我的函數:

def mangle(s1,s2): 
    s1=list(s1) 
    s2=list(s2) 
    a=" " 
    for i in range(0,min(len(s1),len(s2))):   
    for c in s1: 
     for d in s2: 
     a=a+c+d 
     if len(s1)>len(s2): 
      return a+''.join(s1)[min(len(s1),len(s2)): ] 
     elif len(s1)<len(s2): 
      return a+''.join(s2)[min(len(s1),len(s2)): ] 
     else: 
      return a 

,但它產生的:

hphehohphlhee 

我知道的問題是:

for c in s1: 
 for d in s2: 
  a=a+c+d 

,但我不知道如何解決它

回答

4

你是對的。你不需要迭代兩個字符串。你可以簡單地做這樣的:

def mangle(s1, s2): 
    a = "" 
    for i in range(min(len(s1), len(s2))): 
     a += s1[i] + s2[i] 
    if len(s1) > len(s2): 
     return a + s1[min(len(s1), len(s2)):] 
    elif len(s1) < len(s2): 
     return a + s2[min(len(s1), len(s2)):] 
    return a 

assert(mangle('hello','people') == "hpeelolpole") 

這個程序可以與itertools.izip_longest這樣寫:

try: 
    from itertools import izip_longest as zip # Python 2 
except ImportError: 
    from itertools import zip_longest as zip # Python 3 

def mangle(s1, s2): 
    return "".join(c1 + c2 for c1, c2 in zip(s1, s2, fillvalue='')) 

assert(mangle('hello','people') == "hpeelolpole") 
0
import itertools as IT 
def roundrobin(*iterables): 
    """ 
    roundrobin('ABC', 'D', 'EF') --> A D E B F C 
    http://docs.python.org/library/itertools.html#recipes (George Sakkis) 
    """ 
    pending = len(iterables) 
    nexts = IT.cycle(iter(it).next for it in iterables) 
    while pending: 
     try: 
      for n in nexts: 
       yield n() 
     except StopIteration: 
      pending -= 1 
      nexts = IT.cycle(IT.islice(nexts, pending)) 

print(''.join(roundrobin('hello','people'))) 

產生

hpeelolpole 
+1

這似乎是大規模的矯枉過正。 '''.join(chain(* zip('hello','people')))' – roippi

+0

@roippi:'''.join(chain(* zip('hello','people')))'給出不完整的結果:''hpeelolpol'' – unutbu

+0

這就是爲什麼我們應該使用'izip_longest' /'zip_longest'就像我的回答:) – thefourtheye

0

您需要遍歷字符串並從相同的索引中獲取字符。

def mangle(s1,s2): 
    a="" 
    small = min(len(s1),len(s2)) 
    for i in range(0,small):   
     a = a + s1[i] + s2[i] 
    if small is len(s1): 
     a = a + ''.join(s2[i+1:]) 
    else: 
     a = a + ''.join(s1[i+1:]) 
    return a 
相關問題