Python remove all numbers from a list - python-2.7

I have a list of unicode elements and I'm trying to remove all integer numbers from It.
My code is:
List = [u'123', u'hello', u'zara', u'45.3', u'pluto']
for el in List:
if isinistance(el, int):
List.remove(el)
The code doesn't work, It give me the same list with u'123' include.
What i need is this:
List = [ u'hello', u'zara', u'45.3', u'pluto']
Can somebody hel me?

You list consists of unicode strings which are no instances of int obviously. You can try converting them to int in a helper function and use this as a condition to remove them/ to construct a new list.
def repr_int(s):
try:
int(s)
return True
except ValueError:
return False
original_list = [u'123', u'hello', u'zara', u'45.3', u'pluto']
list_with_removed_ints = [elem for elem in original_list if not repr_int(elem)]

Related

Deleting elements that appeare more than once in the list and leaving only one element

I have a small question.
how can i check if a list has identical elements and if the list has identical elements, how can leave only one of those elements in the list?
For example, i wrote this code:
def courses_per_student(tuple_lst):
courses={}
new_tuple_lst=[]
for i in range(len(tuple_lst)):
new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_lst[i][1]).lower())))
for m in new_tuple_lst:
if not courses.has_key(m[0]):
courses[m[0]]=[m[1]]
else:
courses[m[0]]=courses[m[0]]+[m[1]]
return courses
which for: courses_per_student([("Rina", "Math"), ("Yossi", "Chemistry"), ("Riki", "python"), ("Rina", "math"), ("Yossi", "biology")])
returns:
{'rina': ['math', 'math'], 'yossi': ['chemistry', 'biology'], 'riki': ['python']}
I want that 'math' will appere only once in the list.
thankyou
def uniqode(list):
demolist = []
for el in list:
if el in demolist:
continue
demolist.append(el)
return demolist
...
for m in new_tuple_lst:
if not courses.has_key(m[0]):
courses[m[0]]=[m[1]]
elif m[1] not in courses[m[0]]:
courses[m[0]]=courses[m[0]]+[m[1]]
Use set instead of list should also do it if the order does not matter.

How to convert a list of strings into a dict object with kwarg as the keys?

I have seen similar questions. This one is the most similar that I've found:
Python converting a list into a dict with a value of 1 for each key
The difference is that I need the dict keys to be unique and ordered keyword arguments.
I am trying to feed the list of links I've generated through a scraper into a request command. I understand the request.get() function only takes a URL string or kwarg parameters - hence my need to pair the list of links with keyword arguments that are ordered.
terms = (input(str('type boolean HERE -->')))
zipcity = (input(str('type location HERE -->')))
search = driver.find_element_by_id('keywordsearch')
search.click()
search.send_keys('terms')
location = driver.find_element_by_id('WHERE')
location.click()
location.send_keys('zipcity')
clickSearch = driver.find_element_by_css_selector('#buttonsearch-button')
clickSearch.click()
time.sleep(5)
cv = []
cvDict = {}
bbb = driver.find_elements_by_class_name('user-name')
for plink in bbb:
cv.append(plink.find_element_by_css_selector('a').get_attribute('href'))
cvDict = {x: 1 for x in cv}
print(cvDict)
SOLVED: (for now). Somehow figured it out myself. That literally never happens. Lucky day I guess!
cvDict = {'one': cv[:1],
'tw': cv[:2],
'thr': cv[:3],
'fou': cv[:4],
'fiv': cv[:5],
'six': cv[:6],
'sev': cv[:7],
'eig': cv[:8],
'nin': cv[:9],
'ten': cv[:10],
'ele': cv[:11],
'twe': cv[:12],
'thi': cv[:13],
'fourteen': cv[:14],
'fifteen': cv[:15],
'sixteen': cv[:16],
'seventeen': cv[:17],
'eighteen': cv[:18],
'nineteen': cv[:19],
'twent': cv[:20],
}

PYOMO: Indexing set of tuples

I want to create an indexing set of tuples, i mean if i do:
LINEAS_DOWNSTREAM_BARRA[1] I want to see [(1,3),(1,2),(1,4)].
My code is:
m=ConcreteModel()
m.BARRAS = Set()
m.LINEAS_DOWNSTREAM_BARRA = Set(dimen = 2)
m.LINEAS_DOWNSTREAM_BARRA = Set(m.BARRAS, initialize=lambda m, i:
set(tuple(z) for z in m.LINEAS if (i == z[0])))
And the problem is:
ValueError: The value=(1, 2) is a tuple for
set=LINEAS_DOWNSTREAM_BARRA, which has dimen=1
Thanks!!
You should declare the Set m.LINEAS_DOWNSTREAM_BARRA on a single line. Also, make sure that your lambda function is returning a list of tuples
m.LINEAS_DOWNSTREAM_BARRA = Set(m.BARRAS, dimen=2, initialize=your_lambda_fcn)

python 2.7 find in list fails, but iterating over list finds it

My day for asking for help.
I have a big list of strings, created from a 13225 line text file:
with open(dest_file) as f2:
content_dest = [line.rstrip('\n') for line in f2]
My search string is mp.
Checking for mp in the list fails. All items in the list are
<type str>
When I iterate over the list, mp is found.
I don't see anything obvious (again) why this is so. I'm after a list index so I can mess with the data at index + something by accessing the indices I need in the big list. Since my iterations 'work', I guess my question is how do I get the 'mp in list' code to actually work..? And/or why doesn't mp in list' work?? Many thanks.
mp = 'r1_crvR_2_29040_-8580_180'
chk = mp in content_dest
print '**', chk
for x in content_dest:
chk = mp in x
if chk:
print 'Found:', mp, x
print type(mp), type(x)
for i in range(0, len(content_dest)):
chk = mp in content_dest[i]
if not chk:
pass
else:
print 'Found:', mp, content_dest[i], i
results in:
** False
Found: r1_crvR_2_29040_-8580_180 Name "r1_crvR_2_29040_-8580_180"
<type 'str'> <type 'str'>
Found: r1_crvR_2_29040_-8580_180 Name "r1_crvR_2_29040_-8580_180" 11846
mp in list
this works as: to check if string is in list.
As I can understand from the code above, you have only one line in the file with the requested substring. This line is:
Name "r1_crvR_2_29040_-8580_180"
for easier understanding I'll show you another example:
my_list = ["abc"]
check = 'a' in my_list
what should be the result of check?
False, sure, because we have no this string, a in our list.
To verify if there is some strings which consists of our string we can do:
double_check = any(['a' in x for x in my_list])
double_check will show us if there is some string in our list which consists of the requested string.
There is a difference searching in a list or in the items of a list.
For example,ais not in the list:
>>> L = ['abc', 'xyz']
>>> 'a' in L
False
but it is in one item of the list:
>>> for x in L:
... if 'a' in x:
... print 'found'
...
found
Here:
>>> 'a' in L
is equivalent to:
chk = mp in content_dest
and your loop to the loop above.

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s