[英]Length of string within a list of strings python
我正在遍歷一個列表,該列表試圖從中提取數據,如下所示:
for i in lst:
print(i.split('-'))
... output
['a', 'doa', 'a', 'h5t']
['a', 'rne']
['a', 'ece']
['a', 'ece']
['a', 'tnt', 'c', 'doa', 'd', 'nvc', 'a', 'nnm', 'a', 'h5t']
['a', 'tps']
我的目標是提取每個列表中3個字符長的所有字符串。 如果我做
len(i.split('-'))
在這種情況下,上面看起來像:
4
2
2
2
10
2
在循環中,我只獲得列表中每個唯一字符串的長度。 我的問題是如何獲取每個列表中每個字符串中的字符數?
編輯:
輸出應如下所示:
['doa', 'h5t']
['rne']
['ece']
['ece']
['tnt', 'doa', 'nvc', 'nnm', 'h5t']
['tps']
我的目標是提取每個列表中3個字符長的所有字符串。
嵌套列表推導將解決問題。
>>> l = ['a-bc-def-ghij-klm', 'abc-de' 'fg-hi']
>>> [[x for x in s.split('-') if len(x) == 3] for s in l]
[['def', 'klm'], ['abc']]
這段代碼:
lst = ['a-doa-a-h2t','a-rne','a-ece','a-ece','a-tnt-c-doa-d-nvc-a-nnm-a-h5t','a-tps']
for item in lst:
words = item.split('-')
print([word for word in words if len(word) == 3])
產生類似於您的要求的輸出:
['doa', 'h2t']
['rne']
['ece']
['ece']
['tnt', 'doa', 'nvc', 'nnm', 'h5t']
['tps']
您需要另一個循環來提取拆分中的每個單詞,如下所示:
for item in lst:
for word in item.split('-'):
if len(word) == 3:
print(word)
僅再進行一次迭代:
for i in lst:
for greaterThree in i.split('-')):
if len(greaterThree) >= 3:
print(greaterThree)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.