Converting string to float with error handling inside a list comprehension - python-3.x

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]

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

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

Python 3 list comprehension in list of lists to convert types

Consider the following list of lists:
list1 = [['1.1', '1.2', '1.3'], ['2.1', '2.2', '2.3'], ...]
To comprehend a list of strings to convert them to floats one could use
list1[0] = [float(i) for i in list1[0]]
But my attempt to comprehend a list of lists of floats didn't quite work:
list1 = [[float(j) for j in list1[i]] for i in list1]
due to
TypeError: list indices must be integers or slices, not list
Is there a way to do this sort of list comprehension without using loops explicitly?
[[float(j) for j in i] for i in list1]
shall do it

Invalid Syntax in Python 3 when creating a list of tuples

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

Resources