2017-01-02 59 views
0

我試圖將分解成偶數部分。例如,如果我有['abcdef'],預期的輸出應該是['ab','cd','ef']。我不斷收到相同的輸入第一次測試 'asdfadsf'/在列表中均勻分割字符串:Python

def solution(s): 

    lists = [] 

    for i in s: 
     if len(s) % 2 == 0: 
      lists.append(s) 
      zip(*[iter(lists)]*2) 
     return lists 

test.describe("Example Tests") 

tests = (
    ("asdfadsf", ['as', 'df', 'ad', 'sf']), 
    ("asdfads", ['as', 'df', 'ad', 's_']), 
    ("", []), 
    ("x", ["x_"]), 
) 

for inp, exp in tests: 
test.assert_equals(solution(inp), exp) 
+0

我敢打賭,這裏的提問者是相同的編程過程爲[這傢伙(http://stackoverflow.com/q/41432202/1709587)誰(嚴重)問看起來是在同一個問題表中,大約在發佈這個問題的同一時間的後面的問題。 –

回答

1

試試這個,

def solutions(s): 
    return [j.ljust(2,'_') for j in (s[i:i+2] for i in range(0,len(s),2))] 

結果

In [38]: tests = (
    ....:  ("asdfadsf", ['as', 'df', 'ad', 'sf']), 
    ....:  ("asdfads", ['as', 'df', 'ad', 's_']), 
    ....:  ("", []), 
    ....:  ("x", ["x_"]), 
    ....:) 
In [39]: for inp, exp in tests: 
    ....:  print solutions(inp) == exp 
    ....:  
True 
True 
True 
True 
+0

爲了滿足不均勻長度字符串的測試用例,如果len(s)<2],可以在['as','df','ad','s']中使用s ['s' ' – blacksite

-1

做你想要的是最簡單的方法與range

def chunk(input): 

    if len(input) % 2 == 1: 
     input += '_' 

    output = [input[idx:idx+2] for idx in range(0, len(input), 2] 
    return output