Add 2 list of floats together - python

How do i Add 2 lists that both have floats in them. Like how do I actually add the numbers?
Ive tried using
sum(list1, list2) but that did not work
I've also tried
list1+list2 but that didn't work either.

This sounds like a time for a list comprehension.
a = [1.0, 2.0, 3.0]
b = [1.1, 2.2, 3.3]
[x+y for x,y in zip(a,b)]
Or for functional programming.
import operator
map(operator.add, a, b)

The zip method will do. It will combine all elements of a particular index. And since all of them are floating points, just add the values
l1=[1.5,3.2,5.0,3.5]
l2=[8.5,4.7,2.5,7.6]
l3=[i+j for i,j in zip(l1,l2)]
print(l3)

Related

Element-wise appending of 2D lists? [duplicate]

This question already has answers here:
Python: merge nested lists
(4 answers)
Closed 9 months ago.
I want to concatenate 2D lists to the end of a list_log, as follows:
list_log = []
list1 = [[0.0], [1.7], [8.4], [20.1], [29.3], [41.8], [74.1], [61.9]]
list2 = [[1.0], [3.6], [13.5], [31.5], [50.3], [64.4], [93.3], [113.8]]
list_log.append(list1)
list_log.append(list2)
Desired result:
list_log = [[0.0, 1.0], [1.7, 3.6], [8.4, 13.5], [20.1, 31.5], [29.3, 50.3], [41.8, 64.4], [74.1, 93.3], [61.9, 113.8]]
Actual result: list_log = [[[0.0], [1.7], [8.4], [20.1], [29.3], [41.8], [74.1], [61.9]], [[1.0], [3.6], [13.5], [31.5], [50.3], [64.4], [93.3], [113.8]]]
I've also tried getting this result using list comprehension, as follows:
list_log2 = [[[i, j] for i in list1[c] for j in list2[c]] for c in range(8)]
But this gives the following result: list_log2 = [[[0.0, 1.0]], [[1.7, 3.6]], [[8.4, 13.5]], [[20.1, 31.5]], [[29.3, 50.3]], [[41.8, 64.4]], [[74.1, 93.3]], [[61.9, 113.8]]], so with too many brackets.
Also, the example above uses only two lists, but in reality I have thousands of these lists coming in one after the other, and which I need to append to the end of the list_log one-by-one. Because of this I'm reluctant to use list comprehension as shown above, because this basically re-generates the entire log_list2 each time I append a new list, which isn't very efficient. That's why I'm trying to make this happen with .append() instead, as adding one element to the end of a list is computationally much less intensive than re-creating the entire log each time.
So ideally I'd like to make this work with .append() (or similar stuff like .extend()), but I'm open to all suggestions. Thanks in advance!
You can do it using zip() and a list comprehension:
[[*i, *j] for i, j in zip(list1, list2)]
Output:
[[0.0, 1.0],
[1.7, 3.6],
[8.4, 13.5],
[20.1, 31.5],
[29.3, 50.3],
[41.8, 64.4],
[74.1, 93.3],
[61.9, 113.8]]
list1 = [[0.0], [1.7], [8.4], [20.1], [29.3], [41.8], [74.1], [61.9]]
list2 = [[1.0], [3.6], [13.5], [31.5], [50.3], [64.4], [93.3], [113.8]]
print([i+j for i,j in zip(list1,list2)])
>>>[[0.0, 1.0], [1.7, 3.6], [8.4, 13.5], [20.1, 31.5], [29.3, 50.3], [41.8, 64.4], [74.1, 93.3], [61.9, 113.8]]

How to pick same values in a list if the list contain floating numbers

In the following code I want to check how many unique values are in the list and this can be done in for loop. After knowing the number of unique values I want to see how many times a single unique values appear in a and then I want to count their number. Can someone please guide me how to do that. List contains floating points. What if I convert it in numpy array and then find same values.
`a= [1.0, 1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 3.0, 3.0]
list = []
for i in a:
if i not in list:
list.append(i)
print(list)
for j in range(len(list))
g= np.argwhere(a==list[j])
print(g)`
You can use np.unique to get it done
np.unique(np.array(a),return_counts=True)
You can also do it using counters from collections
from collections import Counter
Var=dict(Counter(a))
print(Var)
The primitive way is to use loops
[[x,a.count(x)] for x in set(a)]
If you are not familiar with list comprehensions, this is its explaination
ls=[]
for x in set(a):
ls.append([x,a.count(x)])
print(ls)
If you want it using if else,
counter = dict()
for k in a:
if not k in counter:
counter[k] = 1
else:
counter[k] += 1
print(counter)

Python print nth element from list of lists [duplicate]

This question already has answers here:
How to print column in python array?
(2 answers)
Closed 5 years ago.
I have the following list:
[[50.954818803035948, 55.49664787231189, 8007927.0, 0.0],
[50.630482185654436, 55.133473852776916, 8547795.0, 0.0],
[51.32738085400576, 55.118344981379266, 6600841.0, 0.0],
[49.425931642638567, 55.312890225131163, 7400096.0, 0.0],
[48.593467836476407, 55.073137270550006, 6001334.0, 0.0]]
I want to print the third element from every list. The desired result is:
8007927.0
8547795.0
6600841.0
7400096.0
6001334.0
I tried:
print data[:][2]
but it is not outputting the desired result.
Many way to do this. Here's a simple list way, without an explicit for loop.
tt = [[50.954818803035948, 55.49664787231189, 8007927.0, 0.0], [50.630482185654436, 55.133473852776916, 8547795.0, 0.0], [51.32738085400576, 55.118344981379266, 6600841.0, 0.0], [49.425931642638567, 55.312890225131163, 7400096.0, 0.0], [48.593467836476407, 55.073137270550006, 6001334.0, 0.0]]
print [x[2] for x in tt]
> [8007927.0, 8547795.0, 6600841.0, 7400096.0, 6001334.0]
And making is safe for potentially shorted lists
print [x[2] for x in tt if len(tt) > 3]
More sophisticated output (python 2.7), prints values as newline (\n) seperated
print '\n'.join([str(x[2]) for x in tt])
> 8007927.0
> 8547795.0
> 6600841.0
> 7400096.0
> 6001334.0
Try this:
for item in data:
if len(item) >= 3: # to prevent list out of bound exception.
print(int(item[2]))
map and list comprehensive have been given, I would like to provide two more ways, say d is your list:
With zip:
zip(*d)[2]
With numpy:
>>> import numpy
>>> nd = numpy.array(d)
>>> print(nd[:,2])
[ 8007927., 8547795., 6600841., 7400096., 6001334.]
Maybe you try a map function
In python 3:
list(map(lambda l: l[2], z))
In python 2:
map(lambda l: l[2], z)
In order to print the nth element of every list from a list of lists, you need to first access each list, and then access the nth element in that list.
In practice, it would look something like this
def print_nth_element(listset, n):
for listitem in listset:
print(int(listitem[n])) # Since you want them to be ints
Which could then be called in the form print_nth_element(data, 2) for your case.
The reason your data[:][2] is not yielding correct results is because data[:] returns the entire list of lists as it is, and then executing getting the 3rd element of that same list is just getting the thirst element of the original list. So data[:][2] is practically equivalent to data[2].

Convert elements within an array into floats in python

Hi I am quite new to python and what I want to do is simple but I just can't seem to get around it.
I have a simple array as shown below:
A1 = [('1.000000', '4.000000'), ('2.000000', '5.000000'), ('3.000000', '6.000000'), ('1.000000', '4.000000'), ('2.000000', '5.000000'), ('3.000000', '6.000000')]
I want to change all elements within the array into floats so I can do calculations on them (such as sum etc.). The end results should look something like this:
A2 = [(1.000000, 4.000000), (2.000000, 5.000000), (3.000000, 6.000000), (1.000000, 4.000000), (2.000000, 5.000000), (3.000000, 6.000000)]
I have tried the following:
A2 = [float(i) for i in A1]
however I get the error:
TypeError: float() argument must be a string or a number
Could anyone point me towards a solution.
Thanks in advance
Here's one pretty simple way:
>>> [map(float, x) for x in A1]
[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0], [1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]
I like it's because it's short (some would say terse) and since using map() makes it not hardcode or be explicit about the expected format of each x, it just says that it assumes A1 to be a list of sequences.
I have no idea how this compares performance-wise to other solutions (such as the more explicit [(float(x), float(y) for (x, y) in A1] seen below).
Each element of A1 is a tuple ('1.000000', '4.000000'). You will have to convert each item of the tuple:
A2 = [(float(i), float(j)) for (i, j) in A1]
You need to iterate over the inner tuples as well.
A2 = [tuple(float(s) for s in i) for i in A1]

Average of two consecutive elements in the list in Python

I have a list of even number of float numbers:
[2.34, 3.45, 4.56, 1.23, 2.34, 7.89, ...].
My task is to calculate average of 1 and 2 elements, 3 and 4, 5 and 6, etc. What is the short way to do this in Python?
data = [2.34, 3.45, 4.56, 1.23, 2.34, 7.89]
print [(a + b) / 2 for a, b in zip(data[::2], data[1::2])]
Explanation:
data[::2] is the elements 2.34, 4.56, 2.34
data[1::2] is the elements 3.45, 1.23, 7.89
zip combines them into 2-tuples: (2.34, 3.45), (4.56, 1.23), (2.34, 7.89)
If the list is not too long, Paul Draper's answer is easy. If it is really long, you probably want to consider one of two other options.
First, using iterators, you can avoid copying around giant temporary lists:
avgs = [(a + b) / 2 for a, b in zip(*[iter(data)]*2)]
This does effectively the same thing, but lazily, meaning it only has to store one value at a time in memory (well, three values—a, b, and the average) instead of all of them.
iter(data) creates a lazy iterator over the data.
[iter(data)]*2 creates a list with two references to the same iterator, so when one advances, the other does as well.
Then we're using the same zip and list comprehension that Paul already explained so well. (In Python 2.x, as opposed to 3.x, zip is not lazy, so you're want to use itertools.izip rather than zip.)
If you don't actually need the result list, but just something you can iterate over, change the outer square brackets to parentheses and it becomes a generator expression, meaning it gives you an iterator instead of a list, and you're not storing anything at all.
Notice that the itertools docs have a recipe for a grouper that does the tricky bit (and you can also find it in the third-party module more-itertools), so you can just write grouper(data, 2) instead of zip(*[iter(data)]*2), which is certainly more readable if you're doing it frequently. If you want more explanation, see How grouper works.
Alternatively, you could use NumPy arrays instead of lists:
data_array = np.array(data)
And then you can just do this:
avg_array = (data_array[::2] + data_array[1::2]) / 2
That's not only simpler (no need for explicit loops), it's also about 10x faster, and takes about 1/4th the memory.
If you want to generalize this to arbitrary-length groups…
For the iterator solution, it's trivial:
[sum(group) / size for group in zip(*[iter(data)]*size)]
For the NumPy solution, it's a bit trickier. You have to dynamically create something to iterator over data[::size], data[1::size], …, data[size-1::size], like this:
sum(data[x::size] for x in range(size)) / size
There are other ways to do this in NumPy, but as long as size isn't too big, this will be fine—and it has the advantage that the exact same trick will work for Paul Draper's solution:
[sum(group) / size for group in zip(*(data[x::size] for x in range(size)))]
s= [2.34, 3.45, 4.56, 1.23, 2.34, 7.89, ...]
res= [(s[i]+s[i+1])/2 for i in range(0, len(s)-1, 2)]
Using NumPy to find the mean/average of consecutive two values this is more efficient in terms of Time and Space Complexity:
data=np.array([1,2,3,4,5,6])
k=2 #In your case
data1=np.mean(data.reshape(-1, k), axis=1)
Just use index for the task.
For simple example,
avg = []
list1 = [2.34, 3.45, 4.56, 1.23, 2.34, 7.89]
for i in range(len(list1)):
if(i+1 < len(list1):
avg.append( (list1[i] + list1[i+1]) / 2.0 )
avg2 = []
avg2 = [j for j in avg[::2]]
avg2 is what you want. This maybe easy to understand..

Categories