【发布时间】:2017-05-15 12:14:21
【问题描述】:
我需要在 python 上将字符串 'abcdef' 放入列表 ['ab', 'cd', 'ef']
我尝试使用list(),但它返回['a', 'b', 'c', 'd',' 'e, 'f']
有人可以帮忙吗?
【问题讨论】:
标签: python
我需要在 python 上将字符串 'abcdef' 放入列表 ['ab', 'cd', 'ef']
我尝试使用list(),但它返回['a', 'b', 'c', 'd',' 'e, 'f']
有人可以帮忙吗?
【问题讨论】:
标签: python
你可以使用zip:
s = "abcdef"
[''.join(x) for x in zip(s[::2], s[1::2])]
# ['ab', 'cd', 'ef']
或者
[s[i:i+2] for i in range(0, len(s), 2)]
# ['ab', 'cd', 'ef']
【讨论】:
如果你不介意额外的功能,你可以使用这样的东西:
def grouper(string, size):
i = 0
while i < len(string):
yield string[i:i+size]
i += size
这是一个生成器,因此您需要收集它的所有部分,例如使用list:
>>> list(grouper('abcdef', 3))
['abc', 'def']
>>> list(grouper('abcdef', 2)) # <-- that's what you want.
['ab', 'cd', 'ef']
【讨论】: