繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM