[英]Covert a string into list & sublist with characters sepration in python
将字符串"Welcome to Baramati"
隐藏到列表和子列表中(例如:第一个列表有 3 个字母['W','E','L']
。第二个列表有 4 个字母['C','O','M','E']
,第三个列表有 5 个字母,第六个列表有 6 个字母。
这是使用itertools.count
一种实现:
import itertools
s = "Welcome to Baramati"
lst = [c for c in s if c != ' '] # list-ify
cnt = itertools.count(start=3)
output = []
while lst:
output.append(lst[:(length := next(cnt))])
lst = lst[length:]
print(output) # [['W', 'e', 'l'], ['c', 'o', 'm', 'e'], ['t', 'o', 'B', 'a', 'r'], ['a', 'm', 'a', 't', 'i']]
显然这也使用了海象运算符:=
,它在 python 3.8+ 中可用。
此外,这可能会稍微降低内存效率,因为它会生成一个临时列表。 但 tbh 我个人喜欢使用while something:
模式。 :)
您可以使用生成器函数和一些itertools
:
from itertools import count, islice
def chunks(s, start=3):
i = iter(s.replace(" ", ""))
for c in count(start):
if not (chunk := [*islice(i, c)]):
return
yield chunk
[*chunks('Welcome to Baramati')]
# [['W', 'e', 'l'], ['c', 'o', 'm', 'e'], ['t', 'o', 'B', 'a', 'r'], ['a', 'm', 'a', 't', 'i']]
你可以用replace(' ', '')
来做到这一点,然后只使用 while 并得到你想要的切片,如下所示:
st = 'Welcome to Baramati'
st = st.replace(' ', '')
i = 0
j = 3
res = []
while i<len(st):
res.append([s for s in st[i:i+j]])
i = i+j
j += 1
print(res)
输出:
[['W', 'e', 'l'],
['c', 'o', 'm', 'e'],
['t', 'o', 'B', 'a', 'r'],
['a', 'm', 'a', 't', 'i']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.