简体   繁体   中英

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. 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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