Python nested list comprehension - python-3.x

in my code i have created a nested list via list comprehension containing hex numbers. My next step was to calculate the decimal value of these hex numbers.
My last step was removing the () brackets of each element, because my former method created tupels for each list element.
My question here is, can i combine all three steps into one big step and if yes, will it be more efficient in computing ?
My code looks like this:
from struct import unpack
from codecs import decode
self.step1 = [[self.inputlist[self.otherlist[i]+k] for i in range(len(self.otherlist))]
for k in range(asd)]
self.step2 = [[unpack("<B",decode(x,"hex")) for x in y] for y in self.step1]
self.step3 = [[p[0] for p in q] for q in self.step2]
this code worked fine (i shortened it and am not showing how self.inputlist,otherlist,asd are defined). I am just curious if i can put self.step1, self.step2,self.step3 into one nested list comprehension.

Related

On a dataset made up of dictionaries, how do I multiply the elements of each dictionary with Python'

I started coding in Python 4 days ago, so I'm a complete newbie. I have a dataset that comprises an undefined number of dictionaries. Each dictionary is the x and y of a point in the coordinates.
I'm trying to compute the summatory of xy by nesting the loop that multiplies xy within the loop that sums the products.
However I haven't been able to figure out how to multiply the values for the two keys in each dictionary (so far I only got to multiply all the x*y)
So far I've got this:
If my data set were to be d= [{'x':0, 'y':0}, {'x':1, 'y':1}, {'x':2, 'y':3}]
I've got the code for the function that calculates the product of each pair of x and y:
def product_xy (product_x_per_y):
prod_xy =[]
n = 0
for i in range (len(d)):
result = d[n]['x']*d[n]['y']
prod_xy.append(result)
n+1
return prod_xy
I also have the function to add up the elements of a list (like prod_xy):
def total_xy_prod (sum_prod):
all = 0
for s in sum_prod:
all+= s
return all
I've been trying to find a way to nest this two functions so that I can iterate through the multiplication of each x*y and then add up all the products.
Make sure your code works as expected
First, your functions have a few mistakes. For example, in product_xy, you assign n=0, and later do n + 1; you probably meant to do n += 1 instead of n + 1. But n is also completely unnecessary; you can simply use the i from the range iteration to replace n like so: result = d[i]['x']*d[i]['y']
Nesting these two functions: part 1
To answer your question, it's fairly straightforward to get the sum of the products of the elements from your current code:
coord_sum = total_xy_prod(product_xy(d))
Nesting these two functions: part 2
However, there is a much shorter and more efficient way to tackle this problem. For one, Python provides the built-in function sum() to sum the elements of a list (and other iterables), so there's no need create total_xy_prod. Our code could at this point read as follows:
coord_sum = sum(product_xy(d))
But product_xy is also unnecessarily long and inefficient, and we could also replace it entirely with a shorter expression. In this case, the shortening comes from generator expressions, which are basically compact for-loops. The Python docs give some of the basic details of how the syntax works at list comprehensions, which are distinct, but closely related to generator expressions. For the purposes of answering this question, I will simply present the final, most simplified form of your desired result:
coord_sum = sum(e['x'] * e['y'] for e in d)
Here, the generator expression iterates through every element in d (using for e in d), multiplies the numbers stored in the dictionary keys 'x' and 'y' of each element (using e['x'] * e['y']), and then sums each of those products from the entire sequence.
There is also some documentation on generator expressions, but it's a bit technical, so it's probably not approachable for the Python beginner.

Append list called with iterate

I have a simple issue with my code in Python 3.6.
I am reading a csv and storing int values in a list called Total.
I ask Python user to enter a number n=.. (in this example n=9).
I create n (9) empty list with :
for j in range (1,n+1):
command=""
command="list"+str(j)+"=[]
Now, I have list1, list2, ... list9
Then, I want to append these lists by reading Total starting at different elements and reading each n (9) elements.
For example:
list1=[Tot[0],Tot[8]...] list2=[Tot[1],Tot[9],...]
To do so, I want to something like
for k in range (0,n):
for a in range (0+k,len(Total),n):
listk.append(Total[a])
My problem is here, Python doesn't recognise the integer in listk such as:
list1, ... list9
Is there a certain way to do it ? Maybe by using a class ?
For your problem I suggest using a dictionary. A dictionary is a type of data structure in python that allows to store pairs of information - for example lists and their names. This way you can create n separate named lists, store them all inside one dictionary, and append them as necessary. To start at different indices, I make use of the modulo operator.
This should do the trick:
# shorthand syntax for creating a dictionary with n empty lists: list1,...,listn
lists = {"list" + str(i + 1): [] for i in range(n)}
for k in range(n):
list = lists.get("list" + str(k + 1))
for j in range(n):
list.append(Total[(j + k) % n])
A few sidenotes:
It seems you have a few misunderstandings concerning Python syntax. When you declare the variable "command" inside your loop, Python is saving a pointer to a specific place in stack memory. However you are inside a loop, so "command" is overwritten in every iteration of the loop, and the old pointer is lost.
The following line:
command="list"+str(j)+"=[]
is invalid in Python. The syntax to create lists using square brackets is:
variable = [item1, item2, item3] # or variable = [] for an empty list
You cannot mix between strings and list creation in the way you attempted to.

Transform a Binary Number into a Decimal without recursivity [HASKELL]

I haven't found a way to solve this. I have a list of integer, where which element of the list is a binary digit (0 or 1) so I need to design a function which transforms this list of integers into the proper decimal number.
Example:
Input: [0,1,0]
Output: 2
But there is a specific condition, it is neccesary to use list of comprehension and you can't use recursivity.
The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.
Thank you
The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.
You can, by using zip and a range, you generate 2-tuples that carry the index, like:
[(idx, val) | (idx, val) <- zip [0..] bin]
will produce a list of 2-tuples: the first element containing the element, and the second the element of data at that position.
So if bin = [0,1,0], then the above list comprehension will result in:
Prelude> [(idx, val) | (idx, val) <- zip [0..] bin]
[(0,0),(1,1),(2,0)]
Since this seems to be the "core problem", I propose that you aim to solve the rest of the problem with the above strategy, or ask a question (edit this one, or ask a new one) if you encouter other problems.

Simple adding two arrays using numpy in python?

This might be a simple question. However, I wanted to get some clarifications of how the following code works.
a = np.arange(8)
a
array([1,2,3,4,5,6,7])
Example Function = a[0:-1]+a[1:]/2.0
In the Example Function, I want to draw your attention to the plus sign between the array a[0:-1]+a[1:]. How does that work? What does that look like?
For instance, is the plus sign (addition) adding the first index of each array? (e.g 1+2) or add everything together? (e.g 1+2+2+3+3+4+4+5+5+6+6+7)
Then, I assume /2.0 is just dividing it by 2...
A numpy array uses vector algebra in that you can only add two arrays if they have the same dimensions as you are adding element by element
a = [1,2,3,4,5]
b = [1,1,1]
a+b # will throw an error
whilst
a = [1,2,3,4,5]
b = [1,1,1,1,1]
a+b # is ok
The division is also element by element.
Now to your question about the indexing
a = [1,2,3,4,5]
a[0:-1]= [1,2,3,4]
a[1:] = [2,3,4,5]
or more generally a[index_start: index_end] is inclusive at the start_index but exclusive at the end_index - unless you are given a a[start_index:]where it includes everything up to and including the last element.
My final tip is just to try and play around with the structures - there is no harm in trying different things, the computer will not explode with a wrong value here or there. Unless you trying to do so of course.
If arrays have identical shapes, they can be added:
new_array = first_array.__add__(second_array)
This simple operation adds each value from first_array to each value in second_array and puts result into new_array.

Python For Loop - Switching from PHP

I am new to python and usually use PHP. Can someone please clear me structure of For loop for python.
numbers = int(x) for x in numbers
In PHP everything realted to For loop used to inside the body. I can't understand why methods are before for loop in python.
First of all the statement is missing brackets:
numbers = [int(x) for x in numbers]
This is called a list comprehension and it is the equivalent of:
numbers = []
for x in numbers:
numbers.append(int(x))
Note that you can also use comprehensions as generator expressions, in which case the [] become ():
numbers = (int(x) for x in numbers)
which is the equivalent of:
def numbers(N):
for x in N:
yield int(x)
This means that the for loop will only execute one yield at the time as it is being processed. In other words, while the first example builds a list in memory, a generator returns one element at a time when executed. This is great to process large lists where you can generate one element a time without getting everything into memory (e.g. processing a file line-by-line).
So as you can see comprehensions and generator expressions are a great way to reduce the amount of code required to process lists, tuples and any other iterable.

Resources