Unpack value into multiple variable in python - python

Below code works. However I cannot re-create it/not understand it. Could someone pls help to write all lines to complete the code.
value = #something
var1, var2 = unpack("b8s",value)
That means, here one value is being put into two variables. Can someone give an example, how its possible?
Many thanks in advance.

You're over complicating it by having a loop at all.
var1, var2 = tuple
This is just a syntax thing you can do in python. Note that you must unpack the entire tuple; the number of variables on the left-hand side must be equal to the number of values in the tuple.
Example
myTuple = ("hi","i","am","tuple")
first,second,third,fourth = myTuple
print first
>>hi
print second
>>i
print third
>>am
print fourth
>>tuple
Not allowed
myTuple = ("hi","i","am","tuple")
first,second = myTuple
>>Exception

The unpack method is coming from the struct module, which is lets you treat a Python string like packed binary data. The unpack('b8s', value) call is telling unpack to treat value like a binary string containing one unsigned char (using 'b'), which will be unpacked as the integer value of the char, followed by a char[8] (using '8s'), meaning a char string of length 8. That gets unpacked as a Python string. So a full example would look like this:
>>> from struct import unpack
>>> s = "abcdefgty"
>>> int_char, my_str = unpack("b8s", s)
>>> print int_char
97 # 97 is the ascii code of 'a'
>>> print my_str
bcdefgty

If you have a tuple as
t = (1, 2, "a")
you can unpack it like this:
a, b, c = t
print "a=", a
which prints
a= 1

What is happening is: unpack process the contents of elem and returning a tuple with 2 items. Each item is assigned to a different variable.
it's the same:
unpacked_value = unpack("b8s",elem)
var1 = unpacked_value[0]
var2 = unpacked_value[1]
Using diffentd values and variables:
my_tuple = (1, 2)
var1, var2 = my_tuple
print var1 #outputs 1
print var2 #outputs 2

Related

Can't Print array element names (python) [duplicate]

This question already has answers here:
How can you print a variable name in python? [duplicate]
(8 answers)
Closed 3 months ago.
I have an array of points and I'm looking to print the name of the points instead of the actual points.
A = (2,0)
B = (3, 4)
C = (5, 6)
array1 = [A, B, C]
when I do print(array1[0]) it ends up printing the values. But I want to print the letters such as A, B or C. How would I print the letters instead?
I've also tried print(array1) and it also just prints all the values instead.
A variable doesn't usually contain its own name. This is simply something you can use to target whatever value that is being referenced.
Obviously, the best answer will be related to the really why you want to print "A". If you just want to print the letter "A", then simply do:
print("A")
Obviously, that doesn't scale well depending on the reason why you want to print the name of the variable.
Instead, why don't you use a dictionary? A dictionary is a structure that contains a list of keys that each reference a different value.
dictionary = {"A": (2, 0), "B": (3, 4), "C": (5, 6)}
You can reference each tuple by using the key instead of an index.
print(dictionary["A"])
Will return (2,0)
If you want to print the first value of "B", you simply do dictionary["A"][0].
Alright, now, for the good stuff. Let's say that you want to print all keys AND their values together, you can use the items() method like this:
for key, value in dictionary.items():
print(f"{key}={value}")
What happens if that items() will return a generator of tuples that contains both the keys and their corresponding value. In this way, you And you can use both the key and the value to do whatever you want with them.
By the way, the f in front of the string tells python that this is a formatted string and will compute anything written in between curly brackets and include them as part of the string. In this case, the code written above will output the following:
A=(2,0)
B=(3,4)
C=(5,6)
Try writing array1=["A", "B", "C"] instead of array1=[A, B, C]. A, B, and C are variables so they represent their value, if you want the letters A, B, and C you should use strings instead.

How to access an array using raw_input in python

So, I have a python script which requires an input from the terminal. I have 20 different arrays and I want to print the array based on the input.
This is the code minus the different arrays.
homeTeam = raw_input()
awayTeam = raw_input()
a = (homeTeam[0])+(awayTeam[3])/2
b = (hometeam[1])+(awayTeam[2])/2
So, effectively what I want to happen is that homeTeam/awayTeam will take the data of the array that is typed.
Thanks
You may take input as the comma separated (or anything unique you like) string. And call split on that unique identifier to get list (In Python array and list are different).
Below is the example:
>>> my_string = raw_input()
a, b, c, d
>>> my_list = my_string.split(', ')
>>> my_list
['a', 'b', 'c', 'd']
Since you are having your list now, you already know what you need to do with it.
Alternatively, you may also extract list from raw_input by using eval. But it is highly recommended not to use eval. Read: Is using eval in Python a bad practice?
Below is the example:
>>> my_list = eval(raw_input())
[1, 2, 3, 4, 5]
>>> my_list[2]
3
Instead of 20 individual arrays you could use a dictionary.
d = {"team1": "someValue",
"team2": "anotherValue",
...
}
Then you can retrieve the values of a team by its name:
x = raw_input("team1")
d[x] will now return "someValue".
In your particular case, you can use arrays for the values of the dictionary, for example:
d = {"team1": [value1, value2, ...],
"team2": [...],
...
}
Now d[x] returns the array [value1, value2, ...].
Complete example
Finally, you could wrap all of this into a single function f:
def f():
homeTeam = d[raw_input("Enter home team: ")]
awayTeam = d[raw_input("Enter away team: ")]
a = (homeTeam[0] + awayTeam[3])/2
b = (homeTeam[1] + awayTeam[2])/2
return a, b
By calling f() the user will be prompted for two team names. And the function will return the values of both teams in form of a tuple.
You can take raw_input() as string and then you can use split function to make it array. While doing arithmetic stuff you need to do type casting. for example,
homeTeam = raw_input() ### 1,2,3,4
homeTeam = homeTeam.split(",")
awayTeam = raw_input() ### 5,6,7,8
awayTeam = awayTeam.split(",")
a = (int(homeTeam[0]) + int(awayTeam[3]))/2
b = (int(hometeam[1]) + int(awayTeam[2]))/2

How to make list variable names into strings

I think this should be simple but I'm not sure how to do it. I have a tuple of list variables:
A = (a,b,c)
where
a = [1,2,3,...]
b = [2,4,6,4,...]
c = [4,6,4,...]
And I want to make a tuple or list where it is the names of the variables. So,
A_names = ('a','b','c')
How could I do this? My tuple will have more variables and it is not always the same variables. I tried something like
A_names = tuple([str(var) for var in A])
but this did not work.
My connection was messed up so I couldn't post this earlier but I believe this solves your problem with out using a dictionary.
import inspect
def retrieve_name(var):
local_vars = inspect.currentframe().f_back.f_locals.items()
return [var_name for var_name, var_val in local_vars if var_val is var]
a = [1,2,3]
b = [2,4,6,4]
c = [4,6,4]
a_list = (a,b,c)
a_names = []
for x in a_list:
a_names += (retrieve_name(x)[0])
print a_names
outputs ['a', 'b', 'c']
The problem with what you are asking is that doing A = (a, b, c) does not assign the variables "a", "b" and "c" to the tuple A. Rather, you are creating a new reference to each of the objects referred to by those names.
For example, if I did A = (a,), a tuple with a single object. I haven't assigned the variable "a". Instead, a reference is created at position 0 in the tuple object. That reference is to the same object referred to by the name a.
>>> a = 1
>>> b = 2
>>> A = (a, b)
>>> A
(1, 2)
>>> a = 3
>>> A
(1, 2)
Notice that assigning a new value to a does not change the value in the tuple at all.
Now, you could use the locals() or globals() dictionaries and look for values that match those in A, but there's no guarantee of accuracy since you can have multiple names referring to the same value and you won't know which is which.
>>> for key, val in locals().items():
if val in A:
print(key, val)
('a', 1)
('b', 2)
Assuming you want dynamic/accessible names, you need to use a dictionary.
Here is an implementation with a dictionary:
my_variables = {'a': [1,2,3,...],
'b': [2,4,6,4,...],
'c': [4,6,4,...]}
my_variable_names = my_variables.keys()
for name in my_variable_names:
print(my_variables[name])
Just out of academic interest:
dir() will give you a list of the variables currently visible,
locals() gives the list of local variables
globals() (guess)
Note that some unexpected variables will show up (starting and ending in __), which are already defined by Python.
A = {'a' : [1,2,3,...],
'b' : [2,4,6,4,...],
'c' : [4,6,4,...]}
A_names = A.keys()
for name in A_names:
print(A[name])
Then you can always add a new value to the dictionary by saying:
A.update({'d' : [3,6,3,8,...], 'e' : [1,7,2,2,...]})
Alternatively, you can change the value of an item by going:
A.update({'a' : [1,3,2,...]})
To print a specific value, you can just type:
print(A['c'])

What does 'x, y =' mean in python syntax? [duplicate]

This question already has answers here:
How are tuples unpacked in for loops?
(8 answers)
Closed 9 years ago.
I'm new to python and trying to work my way through http://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/ which has the following line:
result, data = mail.uid('search', None, "ALL") # search and return uids instead
Could someone explain this line?
Thank you.
It means that the function you have called returns an iterable, and the index 0 of the iterable is assigned to x and the index 1 is assigned to y. This is called tuple unpacking.
Eg)
>>> def func(a,b):
... return b,a
...
>>> a = 5
>>> b = 7
>>> a,b = func(a,b)
>>> a
7
>>> b
5
>>> x = func(a,b)
>>> x
(5, 7)
Edit to show that returning multiple values, they are packed as tuple by default and then unpacked at the other end. Since there is only one variable x here, the tuple is assigned to x.
Simple function for swapping two variables(Just for an example) that answers your question
At least, as of python 2.7.x, the function will unpack a tuple of 2 arguments returned from a function. If it returns anything other than 2 arguments in the tuple, I believe it will throw an error if you try to unpack more than this. If it returns 3 arguments and you unpack 2, for example, you will get an exception.
For example:
def func(a):
return (a,a+1,a*2)
a,b,c = func(7)
print a,b
==> 7 8 # NOTE Values
a = func(3)
print a
==> (3, 4, 6) # NOTE: TUPLE
a,b = func(9)
print a,b
==> Exception - ValueError: too many values to unpack
This may be different in 3.0+.
The other answer, that "the function you have called returns an iterable" is a good one. That is what is happening in your specific example. This is what is called "unpacking" in python. The following are examples of unpacking and assignment related to your question:
>>> a,b = 1,2
>>> a
1
>>> b
2
>>> a,b,c = ['do', 're', 'mi']
>>> a
'do'
>>> b
're'
>>> c
'mi'
>>>
This is one of the pretty features of Python syntax. If I am not mistaken, it is also optimized - i.e. the fastest way to achieve the result.

Command Line Python Comma Separated User Input int Values

math.pow (base/exponent) requires comma separated values...working fine for pre-assigned values, but having trouble with user-submitted values (experimenting in command line). Help appreciated as I want to develop this kind of thing eventually making a basic math test.
exp = int(raw_input())
while exp:
print math.pow(int(raw_input))
The errors I'm getting are
ValueError: invalid literal for int() with base 10: '2,3' (which seems weird as this is an exponent, not log function...)
When I try:
exp = (raw_input())
while exp:
print math.pow(exp)
I get error:
pow expected 2 arguments, got 1
Even though I'm submitting 2,3 for example (with comma).
I also tried concatenating the input with .split, but got error regarding pow requiring integers, not "list."
When you enter an input with a comma, you get a tuple. You can either use
eval(raw_input())
Or just
input()
To get this from a string to a usable format. Once you have a tuple, you can use * notation to "unpack" the tuple. So instead of calling math.pow((2, 3)), where the one argument is the tuple (2, 3), you will be calling math.pow(2, 3).
>>> exp = input()
2, 3
>>> math.pow(*exp)
8.0
"2,3" is a string, passing this to a function won't make it act like two different parameters separated by ,(as you expected).
>>> def func(arg):
... print arg
...
>>> func('a, b')
a, b # arg is a variable that stores the passed string
You should convert that string into two numbers first by splitting it at comma first and then applying int() to each if it's item.
>>> import math
>>> math.pow(*map(int, '2,3'.split(',')))
8.0
First split the string at ',' using str.split:
>>> '2,3'.split(',')
['2', '3'] #str.split returns a list
Now as we need integers so apply int() to each value:
>>> map(int, '2,3'.split(',')) #apply int() to each item of the list ['2', '3']
[2, 3]
Now as pow expects two arguments so you can use * notation to unpack this list and pass
the items to math.pow.
>>> math.pow(*[2 , 3])
8.0
A even simpler way would be to use sequence unpacking:
>>> a, b = [2, 3]
>>> math.pow(a, b)
8.0
There's another tool in python library that can convert comma separated items in a string into a tuple:
>>> from ast import literal_eval
>>> literal_eval('1, 2')
(1, 2)
>>> a,b  = literal_eval('1, 2')
>>> a
1
>>> b
2

Categories

Resources