字符串列表中的字符串长度

2024-04-26 22:34:12 发布

您现在位置: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']

Tags: 数据字符串in列表forsplitlsttnt
3条回答

您需要另一个循环来提取拆分中的每个单词,如下所示:

for item in lst:
  for word in item.split('-'):
    if len(word) == 3:
      print(word)

My goal is to extract all the strings within each list that 3 characters long.

嵌套的列表理解就可以了。你知道吗

>>> 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']

相关问题 更多 >