简体   繁体   English

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

[英]Length of string within a list of strings python

I'm iterating over a list that I'm trying to extract data from that looks like this: 我正在遍历一个列表,该列表试图从中提取数据,如下所示:

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

My goal is to extract all the strings within each list that 3 characters long. 我的目标是提取每个列表中3个字符长的所有字符串。 If I do 如果我做

len(i.split('-')) 

in which case the above would look like: 在这种情况下,上面看起来像:

4
2
2
2
10
2

in the loop than I just get the length of each unique string in the list. 在循环中,我只获得列表中每个唯一字符串的长度。 My question is how can I get a count of the characters in each string in each list? 我的问题是如何获取每个列表中每个字符串中的字符数?

EDIT: 编辑:

The output should look like: 输出应如下所示:

['doa', 'h5t']
['rne']
['ece']
['ece']
['tnt', 'doa', 'nvc', 'nnm', 'h5t']
['tps']

My goal is to extract all the strings within each list that 3 characters long. 我的目标是提取每个列表中3个字符长的所有字符串。

A nested list comprehensions will do the trick. 嵌套列表推导将解决问题。

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

This code: 这段代码:

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

produces output something like your requirement: 产生类似于您的要求的输出:

['doa', 'h2t']
['rne']
['ece']
['ece']
['tnt', 'doa', 'nvc', 'nnm', 'h5t']
['tps']

You need another loop to extract each word in the split like so: 您需要另一个循环来提取拆分中的每个单词,如下所示:

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

Only one more iteration: 仅再进行一次迭代:

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