Invalid Syntax in Python 3 when creating a list of tuples - python-3.x

I am trying to create a list of tuples and I am getting Invalid Syntax:
def match_enzymes(strand, enzymes, sequences):
'''(str, list of str, list of str) -> list of (str, list of int) tuples
Return a list of tuples where the first item of each tuple is the name of a restriction enzyme and the second item is the list of indices of the restriction sites that the enzyme cuts.
>>>
>>>
>>>
'''
list_of_tuples = []
for i in range(len(enzymes)):
list_of_tuples.append((enzymes[i], restriction_sites(strand, sequence[i]))
return list_of_tuples

two problems:
1) you are missing the closing parentheses in:
list_of_tuples.append((enzymes[i], restriction_sites(strand, sequence[i])) #<--!!!
2) your code is not indented currently

Related

How to convert a tuple list string value to integer

I have the following list:
l = [('15234', '8604'), ('15238', '8606'), ('15241', '8606'), ('15243', '8607')]
I would like to converted it such that the tuple values are integers and not string. How do I do that?
Desired output:
[(15234, 8604), (15238, 8606), (15241, 8606), (15243, 8607)]
What I tried so far?
l = [('15234', '8604'), ('15238', '8606'), ('15241', '8606'), ('15243', '8607')]
new_list = []
for i in `l:
new_list.append((int(i[0]), i[1]))
print(tuple(new_list))
This only converts the first element i.e. 15234, 15238, 15241, 15243 into int. I would like to convert all the values to int. How do I do that?
The easiest and most concise way is via a list comprehension:
>>> [tuple(map(int, item)) for item in l]
[(15234, 8604), (15238, 8606), (15241, 8606), (15243, 8607)]
This takes each tuple in l and maps the int function to each member of the tuple, then creates a new tuple out of them, and puts them all in a new list.
You can change the second numbers into integers the same way you did the first. Try this:
new_list.append((int(i[0]), int(i[1]))

Get index of a list with tuples in which the first element of the tuple matches pattern

I have a list of tuples:
countries = [('Netherlands','31'),
('US','1'),
('Brazil','55'),
('Russia','7')]
Now, I want to find the index of the list, based on the first item in the tuple.
I have tried countries.index('Brazil'), I would like the output to be 2. But instead, that returns a ValueError:
ValueError: 'Brazil' is not in list
I am aware that I could convert this list into a pd DataFrame and then search for a pattern match within the first column. However, I suspect there is a faster way to do this.
You can use enumerate() to find your index:
Try:
idx = next(i for i, (v, *_) in enumerate(countries) if v == "Brazil")
print(idx)
Prints:
2

Converting string to float with error handling inside a list comprehension

Consider the following list of lists:
list1 = [['1.1','1.2'],['2.1', '2.2'],[''],...]
This list contains lists with empty strings. To convert all strings in this list of lists to floats one could use list comprehension, such as:
[[float(j) for j in i] for i in list1]
(thanks to).
But there is one problem with the lists containing empty strings - they cause an exception:
ValueError: could not convert string to float:
Is there a way to use this kind of list comprehension without using loops explicitly?
Use an if condition inside the inner list comprehension to ignore empty strings:
[[float(j) for j in i if i] for i in list1]
if i will test the "truthiness" of strings. This will only return False for empty strings, so they are ignored.
Or, if you want to be more robust about it, use a function to perform the conversion with exception handling:
def try_convert(val):
try:
return float(val)
except ValueError, TypeError:
pass
[[float(z) for z in (try_convert(j) for j in i) if z] for i in list1]

Getting a list item with the max evaluation in a list of tuples in Python

Given this list of tuples:
my_tuples = [(1,2), (3,4)]
and the following evaluation function:
def evaluate(item_tuple):
return item_tuple[0] * 2
Question: how can I get the list item (tuple) that has the highest evaluation value? (I'm guessing I can use a list comprehension for this)
def max_item(tuples_list, evaluation_fn):
'''Should return the tuple that scores max using evaluation_fn'''
# TODO Implement
# This should pass
assertEqual((3,4), max_item(my_tuples, evaluate))
Correct me if I'm wrong, you want the list of tuples sorted by the result of multiplying one of the values inside the tuple with x (in your example above it would be the first value of the tuple multiplied by 2).
If so, you can do it this way:
from operator import itemgetter
sorted(l, key=itemgetter(0 * 2), reverse=True)
I managed to do it this way:
def max_item(tuples_list, evaluation_fn):
zipped = zip(map(evaluation_fn, tuples_list), tuples_list)
return max(zipped, key=lambda i:i[0])[1]
I don't know if there's a simpler (more pythonic?) way to solve it though.
Edit
I figured how I could use a list comprehension to make it more succinct/readable:
def max_item(tuples_list, evaluation_fn):
return max([(evaluation_fn(i), i) for i in tuples_list])[1]

How to print values of float tuple in list in integer?

list = [(769.0, ), (806.0, )]
In above case, I want to print only 769, 806.
How to print tuple's from list?
I think what you are looking for is how to print the first element in list of tuples?
For a list of tuples with length 2, and you do not care about the 2nd element.
for (fp, _) in list:
print(fp)
For a list of tuples with arbitrary tuple length.
for x in list:
print(x[0])

Resources