我试图将蜇伤分成均匀的部分。例如,如果我有['abcdef']
,则预期输出应为['ab','cd','ef']
。我继续为第一个测试'asdfadsf'/
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 :(得分: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
答案 1 :(得分:-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