How to sum certain floats in a list - python

I wonder how to sum up only the floats in this list,
list = ['abc', 3.0, 2.0, 2.0, 0.0, 1.0, 0.0, 0.0]
I can't find out how to exclude the first string. I would like to do something with
range(1, len(list))
as it will need to work on lists with longer lengths, maybe something similar to it with the same effect? For python 3

You can use a generator in sum() and isinstance() to check if something is a float.
>>> lst = ['abc', 3.0, 2.0, 2.0, 0.0, 1.0, 0.0, 0.0]
>>> sum(x for x in lst if isinstance(x, float))
8.0
Note you should not use list as a variable name as it will overwrite the built in list class.

my_list = ['abc', 3.0, 2.0, 2.0, 0.0, 1.0, 0.0, 0.0]
sum = 0
for i in my_list:
if type(i) is float:
sum += i
print(sum)
This will result the sum to 8.0

Related

Dividing certain members of a list in python

I have a matrix formed by a list of lists and I want to divide each member of the second half of each sublist by the integer in the first 3 members of each sublist. Here is my code:
def matrix():
a=[[12.0, 0.0, 0.0, 12, 156, -108], [0.0, 2.667, 0.0, -5.333, -77.333, 53.333], [0.0, 0.0, -0.0937, -0.0937, -1.4687, 1.0]]
for i in range(len(a)):
a[i] = [v/a[i][i] for v in a[i]]
return a
However, this code divides each entire sublist by the integer found in the first half of each sublist which gives me this output:
[[1.0, 0.0, 0.0, 1.0, 13.0, -9.0], [0.0, 1.0, 0.0, -1.9996250468691417, -28.996250468691414, 19.99737532808399], [-0.0, -0.0, 1.0, 1.0, 15.674493062966913, -10.672358591248665]]
I only want the second part of each sublist divided, not the first half. I need to obtain this output, as you can see the first 3 integers of each sublist must stay the same:
[[12,0,0,1,13,-9],[0,2.667,0,-2,-29,20],[0,0,-0.09375,1,15.6667,-10.6667]]
You can split up your logic into two steps:
Find the integer in the first three numbers.
Divide the second half of each sublist by that number.
def matrix():
a = [[12.0, 0.0, 0.0, 12, 156, -108],
[0.0, 2.667, 0.0, -5.333, -77.333, 53.333],
[0.0, 0.0, -0.0937, -0.0937, -1.4687, 1.0]]
for i in range(len(a)):
divisor = 0
for j in range(3):
if a[i][j]:
divisor = a[i][j]
break
for j in range(len(a[i]) // 2, len(a[i])):
a[i][j] = a[i][j] / divisor
return a
print(matrix())
Output:
[[12.0, 0.0, 0.0, 1.0, 13.0, -9.0], [0.0, 2.667, 0.0, -1.9996250468691417, -28.996250468691414, 19.99737532808399], [0.0, 0.0, -0.0937, 1.0, 15.674493062966913, -10.672358591248665]]

How to find part of series in some series

The question is simple.
Suppose we have Series with this values:
srs = pd.Series([7.0, 2.0, 1.0, 2.0, 3.0, 5.0, 4.0])
How can I find place (index) of subseries 1.0, 2.0, 3.0?
Using a rolling window we can find the first occurrence of a list a.It puts a 'marker' (e.g. 0, any non-Nan value will be fine) at the end (right border) of the window. Then we use first_valid_index to find the index of this element and correct this value by the window size:
a = [1.0, 2.0, 3.0]
srs.rolling(len(a)).apply(lambda x: 0 if (x == a).all() else np.nan).first_valid_index()-len(a)+1
Output:
2
The simplest solution might be to use list comprehension:
a = srs.tolist() # [7.0, 2.0, 1.0, 2.0, 3.0, 5.0, 4.0]
b = [1.0, 2.0, 3.0]
[x for x in range(len(a)) if a[x:x+len(b)] == b]
# [2]
One naive way is to iterate over the series, subset the n elements and compare if they are equal to the given list:
Here the code:
srs = pd.Series([7.0, 2.0, 1.0, 2.0, 3.0, 5.0, 4.0])
sub_list = [1.0, 2.0, 3.0]
n = len(sub_list)
index_matching = []
for i in range(srs.shape[0] - n + 1):
sub_srs = srs.iloc[i: i+n]
if (sub_srs == sub_list).all():
index_matching.append(sub_srs.index)
print(index_matching)
# [RangeIndex(start=2, stop=5, step=1)]
Or in one line with list comprehension:
out = [srs.iloc[i:i+n].index for i in range(srs.shape[0] - n + 1) if (srs.iloc[i: i+n] == sub_list).all()]
print(out)
# [RangeIndex(start=2, stop=5, step=1)]
If you want an explicit list:
real_values = [[i for i in idx] for idx in out]
print(real_values)
# [[2, 3, 4]]

Accessing elements in a nested list

I have elements in a nested list called "train_data" like in the example:
[0] [0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
[1] [0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675, 0]
[2] [0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206, 1]
I would like to access all rows with the first 8 columns (all but the last one), and all rows with only the last column. I need to this without for loops, in a single line of code.
I tried something like this:
print train_data[0][:]
print train_data[:][0]
but this gives me the same result:
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
Could someone help me please?
Edit:
Sorry, the expected output for the first query is:
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494]
[0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675]
[0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206]
and for the second query is:
[0]
[0]
[1]
you can use [:-1] slicing for get all elements except the last one !
>>> l1=[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
>>> l2=[0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675, 0]
>>> l3=[0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206, 1]
>>> l=[l1,l2,l3]
>>> [i[:-1] for i in l]
[[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494], [0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675], [0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206]]
Is there really a good reason to do this in a oneliner? I mean why is that a requirement?
print [i[:-1] for i in l] # All rows with all cols - 1
print [i[-1] for i in l] # All rows with last col
But even if the loop is not explicit with a for, it's implicit as a comprehensive list...
edit: 1 → -1 for second line of code, my mistake
I think you are expecting this
L1 = [x[0:-1] for x in train_data]
L2 = [x[-1] for x in train_data]
for x in L1:
print x
for x in L2:
print [x]

Split list after repeating elements

I have this loop for creating a list of coefficients:
for i in N:
p = 0
for k in range(i+1):
p += (x**k)/factorial(k)
c.append(p)
For example N = [2, 3, 4] would give list c:
[1.0, 2.0, 2.5, 1.0, 2.0, 2.5, 2.6666666666666665, 1.0, 2.0, 2.5, 2.6666666666666665, 2.708333333333333]
I want a way of making separate lists after each 1.0 element. For example a nested list:
[[1.0, 2.0, 2.5], [1.0, 2.0, 2.5, 2.6666666666666665], [1.0, 2.0, 2.5, 2.6666666666666665, 2.708333333333333]]
I was thinking of using an if test, like
for c_ in c:
if c_ == 1.0:
anotherList.append(c_)
This only appends 1.0's though and I don't know how I can make it append everything after a one instead of just 1.0.
you can use itertools.groupby in list comprehension :
>>> [[1.0]+list(g) for k,g in itertools.groupby(l,lambda x:x==1.0) if not k]
[[1.0, 2.0, 2.5], [1.0, 2.0, 2.5, 2.6666666666666665], [1.0, 2.0, 2.5, 2.6666666666666665, 2.708333333333333]]
Try something like
another_list = []
for c_ in c:
if c_ == 1.0:
another_list.append([])
another_list[-1].append(c_)
Thanks for the suggestion #James Jenkinson

Python: how to add first value in each list

A Posn is a list of length two [x,y], where
x and y are both Float values, corresponding to
the x and y coordinates of the point, respectively.
make_posn: float float -> Posn
def make_posn(x_coord, y_coord):
return [x_coord, y_coord]
How do I add all the x-values in a list of Posns?
Ex: [ [3.0, 4.0], [8.0, -1.0], [0.0, 2.0]] would be 11
sum them:
In [2]: sum(x[0] for x in [ [3.0, 4.0], [8.0, -1.0], [0.0, 2.0]])
Out[2]: 11.0
The following piece of code should work for your
_sum = 0.0
for sublist in [ [3.0, 4.0], [8.0, -1.0], [0.0, 2.0]]:
_sum += sublist[0]
It initializes a sum accumulator to zero and then iterates over the sublist elements of the list to add the value of the first element of each list, to the initial sum

Categories

Resources