0
Quick question for python
How do I make a function that takes a list of strings and returns a new list containing all the strings with a length of 3? Def threeChars(li): For i in range(len(st): If char <3 or >3: (Don’t print strings anything less or greater than 3?) not sure how Print(I) Li = [‘hello’, ‘and’, ‘he’, ‘dog’ Print(threeChars(li)) Output[and, dog]
3 ответов
+ 4
The most convenient ones are one-liners so here you go:
List comprehension:
[s for s in strings if len(s) == 3]
Filter:
list(filter(lambda s: len(s) == 3, strings))
So you just return one of those in your function.
There's not much to explain here. I recommend you go read up on list comprehensions because they're useful everywhere.
+ 3
Chris , I can suggest you the filter method. Look at my example. Hope it helps you.
https://code.sololearn.com/cXsYC84Pgsjn/?ref=app
+ 2
you can try this:
def threeChars(str_array):
return [string for string in str_array if len(string) == 3]
or better:
def threeChars(str_array):
return [string for string in str_array if type(string) == str if len(string) == 3]
if you don't like one-liners:
def threeChars(str_array):
result = []
for string in str_array:
if type(string) == str:
if len(string) == 3:
result.append(string)
return result