I have the following code which works well
list = ["age", "test=53345", "anotherentry", "abc"]
val = [s for s in list if "test" in s]
if val != " ":
print(val)
But what I'm trying to do is using the list comprehension as condition for an if else statement as I need to proof more than one word for occurence. Knowing it will not work, I'm searching for something like this:
PSEUDOCODE
if (is True = [s for s in list if "test" in s])
print(s)
elif (is True = [l for l in list if "anotherentry" in l])
print(l)
else:
print("None of the searched words found")
First of all, avoid using reserved words like "list", to name variables. (Reserved words are always branded as blue).
If you need something like this:
mylist = ["age", "test=53345", "anotherentry", "abc"]
keywords = ["test", "anotherentry", "zzzz"]
for el in mylist:
for word in words:
if (word in el):
print(el)
Use this:
[el for word in keywords for el in mylist if (word in el)]
any in python allows you to see if an element in a list satisfies a condition. If so it returns True else False.
if any("test" in s for s in list): # Returns True if "test" in a string inside list
print([s for s in list if "test" in s])
First, please don't use "list" as a variable. There is a built-in function called list()...
Could work like this:
list_ = ["age", "test=53345", "anotherentry", "abc"]
val = [s for s in list_ if "test" in s] #filters your initial "list_" according to the condition set
if val:
print(val) #prints every entry with "test" in it
else:
print("None of the searched words found")
Since a non-empty list tests as True (e.g. if [1]: print('yes') will print 'yes') you can just see if your comprehension is empty or not:
>>> alist = ["age", "test=53345", "anotherentry", "abc"]
>>> find = 'test anotherentry'.split()
>>> for i in find:
... if [s for s in alist if i in s]:i
...
'test'
'anotherentry'
But since it is sufficient to find a single occurance, it would be better to use any like this:
>>> for i in find:
... if any(i in s for s in alist):i
...
'test'
'anotherentry'
Related
I'm trying to reference an object that I'm matching for.
import re
list = ["abc","b","c"]
if any(re.search(r"a",i) for i in list):
print("yes")
print(i)
This works, just not the last print command.
Is there any way to do what I'm trying do to here?
any only tells you whether anything fulfilled the condition, it doesn't let you have the value. The most pythonic way to do that is probably this:
try:
i = next(i for i in list if i == 'a')
print(i)
except StopIteration:
print('No such thing')
If you don't like the exception and would rather use an if:
i = next((i for i in list if i == 'a'), None)
if i:
print(i)
Variables from any() do not bleed out of it's scope - they are only known inside it.
You are just matching simple letters - you can get all items from your list that have this letter in them by using a list comprehension:
my_list = ["abc","b","c","abracadabra"]
with_a = [ item for item in my_list if "a" in item] # or re.find ... but not needed here
# this prints all of them - you can change it to if ...: and print(with_a[0])
# to get only the first occurence
for item in with_a:
print("yes")
print(item)
Output:
yes
abc
yes
abracadabra
My question is how can I find strings in a list that have the same number of characters if my list is...
myList = ["Hello", "How","are", "you"]
and I want it to return the strings that are of value 3
example from above list...
["How","are","you"]
This is what I've tried...
def listNum(myList, x):
for i in range(len(myList)):
if i == x:
return(i)
myList = ["Hello", "How","are", "you"]
x = 3
listNum(myList, x)
Your function is off because you are comparing the list index to the value you are trying to match with i == x. You want to use myList[i] == x. But it seems you actually want to check the length, so len(myList[i]) == x.
However, I prefer iterating over the actual elements in a loop (or list comprehension as noted in comments by Joran Beasley). You also mentioned that you wanted to check if for string of certain length, so you can also add a check for the object type:
def listNum(myList, x):
return [item for item in myList if type(item) is str and len(item) == x]
Use the setdefault() method. This solution should give you a dictionary of all the word lengths mapped to their respective words
CODE
myList = ["Hello", "How","are", "you"]
dict1 = {}
for ele in myList:
key = len(ele)
dict1.setdefault(key, [])
dict1[key].append(ele)
OUTPUT
I guess this is the output you are trying to achieve.
>>> print(dict1)
{5: ['Hello'], 3: ['How', 'are', 'you']}
You can use this to query the dictionary and get the words corresponding to their word lengths. For e.g. dict1[5] would return 'hello'
If you are planning to use it for further enhancement i suggest you make dict in one loop then you can easily retrieve that for any number of characters. if you search for x=3 or 4 each time you have to go through your list. rather then that make dict with one loop.
myList = ["Hello", "How","are", "you"]
data = {}
for i in myList:
if len(i) in data:
data[len(i)].append(i)
else:
data[len(i)] = [i]
# print(data)
x = 3
print(data[x])
output:
['How', 'are', 'you']
I believe you can use Python filter function here.
# list
myList = ["Hello", "How","are", "you"]
# function that examines each element in an array and returns it if True
def filterData(item):
if(len(item) == 3):
return True
else:
return False
# filter function that takes 'function-to-run' and an array
filtered = filter(filterData, myList)
# result
print('The filtered strings are:')
for item in filtered:
print(item)
Hope it helped. Cheers!
You can use the function groupby() with a sorted list:
from itertools import groupby
myList = ["Hello", "How", "are", "you"]
f = lambda x: len(x)
l = sorted(myList, key=f)
r = {k: list(g) for k, g in groupby(l, key=f)}
# {3: ['How', 'are', 'you'], 5: ['Hello']}
r[3]
# ['How', 'are', 'you']
Try this code.
Code
def func_same_length(array,index):
res = [array[i] for i in range(0,len(array)) if len(array[index]) == len(array[i]) and i!=index]
return res
myList = ["Hello", "How", "are", "you"]
resSet = set()
for index in range(0,len(myList)):
res = func_same_length(myList,index)
for i in res:
resSet.add(i)
print(resSet)
Output
{'How', 'are', 'you'}
I have data as below
lst = ['abs', '#abs', '&abs']
I need to replace all parts with # or &. I do like this
new = []
simbol1 = '#'
simbol2 = '&'
for item in lst:
if simbol1 not in item:
if simbol2 not in item:
new.append(item)
But is there more simple way for this loop?
I tried like this
lst = ['abs', '#abs', '&abs']
new = []
simbol1 = '#'
simbol2 = '&'
for item in lst:
if any([simbol1 not in item , simbol2 not in item]):
new.append(item)
But i get
new
['abs', '#abs', '&abs']
What is a correct way to use multiple conditions in this case?
You can use list comprehension & merge the two if's as follows:
>>> lst = ['abs', '#abs', '&abs']
>>> new_lst = [l for l in lst if '#' not in l and '&' not in l]
>>> new_lst
['abs']
>>>
You can also use all() instead of multiple ifs like follows:
>>> lst = ['abs', '#abs', '&abs']
>>> new_lst = [l for l in lst if all(x not in l for x in ['#','&'])]
>>> new_lst
['abs']
>>>
You can just combine two ifs:
if simbol1 not in item and simbol2 not in item:
new.append(item)
lst = ['abs', '#abs', '&abs']
new = []
simbol1 = '#'
simbol2 = '&'
for item in lst:
if all([simbol1 not in item , simbol2 not in item]):
new.append(item)
print (new)
Functionally, you could do
new_list = list(filter(lambda x: all(f not in x for f in ['#', '&']), lst))
as an explanation, the lambda function ensures that none of the forbidden f characters are in string by filtering out all values that evaluate to False. filter returns a generator, so one can make that a list.
lst = ['abs', '#abs', '&abs']
out_lst = [el for el in lst if '#' not in el and '&' not in el]
print(out_lst) # ['abc']
Your code is very close to correct; the only problem is that you got the negation backward.
This:
if any([simbol1 not in item , simbol2 not in item]):
… is asking "are any of these are not in the item?" Just as in English, that's true if one is not in the item, but the other is in the item, which isn't what you want. You only want it to be true if neither is in the item.
In other words, you want either "are all of these not in the item?"
if all([simbol1 not in item, simbol2 not in item]):
… or "are none of these in the item?"
if not any([simbol1 in item, simbol2 in item]):
However, when you only have a fixed list of two things like this, it's usually easier to use and or or instead of any or all—again, just like in English:
if symbol1 not in item and simbol2 not in item:
… or:
if not (simbol1 in item or simbol2 in item):
If, on the other hand, you had a whole bunch of symbols to check, or a list of them that you couldn't even know until runtime, you'd want a loop:
if all(simbol not in item for simbol in (simbol1, simbol2)):
if not any(simbol in item for simbol in (simbol1, simbol2)):
I am able to detect matches but unable to locate where are they.
Given the following list:
['A second goldfish is nice and all', 3456, 'test nice']
I need to search for match (i.e. "nice") and print all the list elements that contain it. Ideally if the keyword to search were "nice" the results should be:
'A second goldfish is nice and all'
'test nice'
I have:
list = data_array
string = str(raw_input("Search keyword: "))
print string
if any(string in s for s in list):
print "Yes"
So it finds the match and prints both, the keyword and "Yes" but it doesn't tell me where it is.
Should I iterate through every index in list and for each iteration search "string in s" or there is an easier way to do this?
Try this:
list = data_array
string = str(raw_input("Search keyword: "))
print string
for s in list:
if string in str(s):
print 'Yes'
print list.index(s)
Editted to working example. If you only want the first matching index you can also break after the if statement evaluates true
matches = [s for s in my_list if my_string in str(s)]
or
matches = filter(lambda s: my_string in str(s), my_list)
Note that 'nice' in 3456 will raise a TypeError, which is why I used str() on the list elements. Whether that's appropriate depends on if you want to consider '45' to be in 3456 or not.
print filter(lambda s: k in str(s), l)
To print all the elements that contains nice
mylist = ['nice1', 'def456', 'ghi789', 'nice2', 'nice3']
sub = 'nice'
print("\n".join([e for e in mylist if sub in e]))
>>> nice1
nice2
nice3
To get the index of elements that contain nice (irrespective of the letter case)
mylist = ['nice1', 'def456', 'ghi789', 'Nice2', 'NicE3']
sub = 'nice'
index_list = []
i = 0
for e in mylist:
if sub in e.lower():
index_list.append(i)
i +=1
print(index_list)
>>> [0, 3, 4]
I have two lists where I am trying to see if there is any matches between substrings in elements in both lists.
["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
["2311","233412","2231"]
If any substrings in an element matches the second list such as "Po2311tato" will match with "2311". Then I would want to put "Po2311tato" in a new list in which all elements of the first that match would be placed in the new list. So the new list would be ["Po2311tato","Pin2231eap","Orange2231edg"]
You can use the syntax 'substring' in string to do this:
a = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
b = ["2311","233412","2231"]
def has_substring(word):
for substring in b:
if substring in word:
return True
return False
print filter(has_substring, a)
Hope this helps!
This can be a little more concise than the jobby's answer by using a list comprehension:
>>> list1 = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
>>> list2 = ["2311","233412","2231"]
>>> list3 = [string for string in list1 if any(substring in string for substring in list2)]
>>> list3
['Po2311tato', 'Pin2231eap', 'Orange2231edg']
Whether or not this is clearer / more elegant than jobby's version is a matter of taste!
import re
list1 = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
list2 = ["2311","233412","2231"]
matchlist = []
for str1 in list1:
for str2 in list2:
if (re.search(str2, str1)):
matchlist.append(str1)
break
print matchlist