Hi there,

I have a mixed list containing strings, integers, strings with numbers both prefix and suffix and mixed case strings as follow:

mixedlist = ["cake", 12, "cakecar", "cAKe", "orange", "apple", "1cake", "cake1"]

I'm trying to filter the list for any element containing "cake" so I get a new list that looks something like this:

newlist = ["cake", "cakecar", "cAKe", "1cake", "cake1"]

So my approach was to:

convert each element in the list to a string (avoiding any integers) using:
stringlist = [str(x) for x in mixedlist]

and then using x.lower() to ignore case.

then for loop'in through the list looking for any element containing "cake"

and finally using newlist.append(x) to append filtered elements to new list


problem is i cant filter out an element that contains "cake" were its with a number i.e. "1cake" or "cake1" nor an element containing cake with anything else i.e. "cakecar"


Any help would be appreciated, cheers!

What is the problem with filtering?

I suppose you have a function, that tells if a list member contains cake. Does this function behave unexpectedly?

I think this function should look like:
ffilt=lambda x: str(x).lower().find("cake")<>-1

Here was my solution to the problem:

word = 'cake'
cakeList = []
mixedList = ["cake", 12, "cakecar", "cAKe", "orange", "apple", "1cake", "cake1"]
for x in mixedList:
    if word in str(x).lower():
        cakeList.append(x)
print cakeList

With the output: ['cake', 'cakecar', 'cAKe', '1cake', 'cake1'] Each element in mixedList is searched for the string 'cake', and if this is True, the element is appended into cakeList.

I am still a n00b at python, so this might not be the most efficient method of solving this problem.

Mine is:

mixedList = ["cake", 12, "cakecar", "cAKe", "orange", "apple", "1cake", "cake1"]
ffilt=lambda x: str(x).lower().find("cake")<>-1  
print filter(ffilt,mixedList)

Here was my solution to the problem:

word = 'cake'
cakeList = []
mixedList = ["cake", 12, "cakecar", "cAKe", "orange", "apple", "1cake", "cake1"]
for x in mixedList:
    if word in str(x).lower():
        cakeList.append(x)
print cakeList

With the output: ['cake', 'cakecar', 'cAKe', '1cake', 'cake1'] Each element in mixedList is searched for the string 'cake', and if this is True, the element is appended into cakeList.

I am still a n00b at python, so this might not be the most efficient method of solving this problem.

Pretty nice code for a noob! You can simplify it a little with list comprehension ...

word = 'cake'
mixedList = ["cake", 12, "cakecar", "cAKe", "orange", "apple", "1cake", "cake1"]

cakeList = [x for x in mixedList if word in str(x).lower()]

print cakeList  # ['cake', 'cakecar', 'cAKe', '1cake', 'cake1']
This question has already been answered. Start a new discussion instead.