2014-03-31 16 views

回答

5

將您的打印放置在循環外部,並將其轉換回字符串而不是字母列表。

def doubleChar(doubleit): 
    doubled = [] 
    for letter in doubleit: 
     doubled.append(letter * 2) 
    print("".join(doubled)) 

doubleChar('the') 

順便說一句甚至沒有必要的功能,簡單的一個班輪:

>>> r = "the" 
>>> "".join(x*2 for x in r) 
'tthhee' 
1

我將與zip做到這一點:

>>> def duplicator(s, n=2): 
...  return ''.join(x for t in zip(*[s] * n) for x in t) 
... 
>>> duplicator('the') 
'tthhee' 
>>> duplicator('potato', 3) 
'pppoootttaaatttooo' 
0
reduce(lambda s, c: s + c + c, "hello", "") 
1

你幾乎沒有。您只需要將不同的條目附加到加倍列表中。

def doubleChar(doubleit): 
    doubled = [] 
    for letter in doubleit: 
    doubled.append(letter * 2) 
    # at this stage you have ['tt', 'hh', 'ee'] 
    # you can join them into a str object 
    return "".join(doubled) 

您還可以使用lambda與理解中結合,做到這一點:

doubleChar = lambda s : "".join([e*2 for e in s]) 

或者你可以保持您的循環,但使用STR對象,而無需通過列表吧:

s = "the" 
d = "" 
for c in s: 
    d = d + e*2 
print(d) 
>> 'tthhee' 
1

只是爲了好玩,這裏是使用擴展切片的不尋常的方式

>>> s='the' 
>>> (s+(' '+s*2)*len(s))[::len(s)+1] 
'tthhee' 
>>> s="hello world" 
>>> (s+(' '+s*2)*len(s))[::len(s)+1] 
'hheelllloo wwoorrlldd' 
相關問題