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)):
Related
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'
Let's say I have this list:
list = ['hello','world','spam','eggs']
and I want to clear everything from that list EXCEPT 'world'.
How do I do this?
You can use list comprehension for this as:
l = ['hello','world','spam','eggs']
only = [item for item in l if item == 'world'] # ['world']
if you want to do it for multiple words you can store you filters as this:
l = ['hello','world','spam','eggs']
filters = ['hello', 'world']
only = [item for item in l if item in filters] # ['hello', 'world']
or you can also use the filter function as this:
l = ['hello','world','spam','eggs']
only = filter(lambda x: x == 'hello', l) # ['hello']
In totaly, consider now to call your varibles by the type name, calling something list override the list constructor, which can lead for other prolbems in the future
another solution is to check if 'world' exists in your list. If not assign an empty list.
list = ['hello','world','spam','eggs']
if 'world' in list:
list = ['world'] * list.count('world')
else:
list = []
print(list)
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 2 lists,
my_list = ['on#3','one',"$", "lo#"]
spl = ["#","$"]
I am trying to get the items in 'my_list' which contains any of the items in spl.
I tried
out_list = [item for item in my_list if item.contains("!".join(spl))]
but this gives error.
My expected output is
out_list = ["on#3","$"]
No such method as item.contains. There's item.__contains__, but you don't need to call that directly.
You want to check if any of the items in spl is contained in the item, use the builtin any:
lst = [item for item in my_list if any(x in item for x in spl)]
# ... if any(item.__contains__(x) for x in spl)]
print(lst)
# ['on#3', '$']
result = [item for item in my_list for s in spl if s in item]
And more human readable form:
result = []
for item in my_list:
for s in spl:
if s in item:
result.append(item)
I have a list:
my_list = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
How can I delete the \t and everything after to get this result:
['element1', 'element2', 'element3']
Something like:
>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']
myList = [i.split('\t')[0] for i in myList]
Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.
for i in list:
newList.append(i.split('\t')[0])
Do not use list as variable name.
You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
Solution with map and lambda expression:
my_list = list(map(lambda x: x.split('\t')[0], my_list))
I had to split a list for feature extraction in two parts lt,lc:
ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)
featsets = [(act_features((lt)),lc)
for lc, lt in ltexts]
def act_features(atext):
features = {}
for word in nltk.word_tokenize(atext):
features['cont({})'.format(word.lower())]=True
return features