將字串"Welcome to Baramati"轉換為串列和子串列(例如:第一個串列有 3 個字母['W','E','L']。第二個串列有 4 個字母['C','O','M','E'],第三個串列有 5 個字母,第六個串列有 6 個字母。
uj5u.com熱心網友回復:
您可以使用生成器函式和一些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']]
uj5u.com熱心網友回復:
你可以做到這一點,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']]
uj5u.com熱心網友回復:
這是使用的一種實作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']]
顯然這也使用了 walrus operator :=,它在 python 3.8 中可用。
此外,這可能會稍微降低記憶體效率,因為它會生成一個臨時串列。但是 tbh 我個人喜歡使用while something:模式。:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340993.html
