I'm trying to create a new list from an original list but am having some difficulties.
The list is as follows list1 = [training, bicycle, working, carrying, bite, eat]
my new list called ing is designed to only sort out the words containing ing within it so the new list should look like this [training, working, carrying]
the code looks as follows
def ing(lists):
b = "ing"
for d in lists:
if b in d:
print(d)
else:
continue
return (lists)
when running this with list1, it pretty much prints out list1 rather than isolating the word containing ing.
The problem area appears to be the line
if b in d:
is there are better way of writing a sorting out a list based on the words within that list as this seems to be the only way
You're never making a new list, only printing things
Try this
list1 = ["training" , "bicycle", "working", "carrying", "bite" , "eat"]
ing = [x for x in list1 if "ing" in x]
print(ing)
Or if you insist on having a function
def filter_ing(l);
return [x for x in l if "ing" in x]
If you want to do with a method call - Just have your method return a new list with elements of the old list satisfying the search criteria.
Something like:
def ing(lists):
b = "ing"
new_list = []
for d in lists:
if b in d:
print(d)
new_list.append(d)
else:
continue
return new_list
list1 = ['training', 'bicycle', 'working', 'carrying', 'bite', 'eat']
new_list = ing(list1)
print new_list
The list output of the code above is:
['training', 'working', 'carrying']
Doing with a list comprehension works as well as shown by @cricket_007
try this one (New way with similarity to you code)
def ing(l):
new=[]
b="ing"
for d in l:
if b in d:
new.append(d)#I am adding the wording ending with 'ing' to a new list
#you were missing appending
print(new)
l= ['training','bicycle','working','carrying','bite','eat']
ing(l)#calling_function
The thing you were missing was that you the list you given doesn't consist of string. To put them in string use ' ' or " " as I have done above.
Also, when you are using return then there should be some thing to hold that specific return. You didn't use such thing.
Still any doubt, Feels free to ask via comment. Happy to help.
You can use regular expressions:
import re
l= ['training','bicycle','working','carrying','bite','eat']
new_l = filter(lambda x:re.findall('ing$', x), l)
Output:
['training', 'working', 'carrying']
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.