Making multiple variables equal to multiple values from a list - python

Is there a way I can use something like this:
a, b, c = [1, 2, 3, 4, 5]
In order to get the values:
a = 1
b = [2, 3]
c = [4, 5]

To break up existing data as needed:
>>> data = [1,2,3,4,5]
>>> a,b,c = data[0],data[1:3],data[3:]
>>> a
1
>>> b
[2, 3]
>>> c
[4, 5]

Related

Isn't there a multidimensional set library in Python?

I want to do a multidimensional set compute.
For example:
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
This one's set.difference is:
c = a - b
c = [1, 2]
But when it's multi-dimensional, I don't know.
How do I do this?
a = [['a',1],['b',2],['c',3]]
b = [['a',2],['c',7],['d',5]]
I want to calculate around a string.
I wish I could get this value.
c = a - b
c = [['b',2]]
You can try
[i for i in a if i[0] in {str(i[0]) for i in a}.difference({str(i[0]) for i in b})]
Output
[['b', 2]]
This code will return the item that is in the list a by the first elements that is not in the b list.

How to get the expected result using list comprehension

I have the following lists
a=[1,2,3]
b=[4,5,6]
c=[a,b]
i need to combine both list a and b.
result should be like [1,2,3,4,5,6]
i tried with list comprehension
[x for x in i for i in c]
output
[3, 3, 4, 4, 5, 5]
How can i get the result as [1,2,3,4,5,6] using list comprehension.
You can just do:
a + b
If you must use list comprehension:
In [10]: a = [1, 2, 3]
In [11]: b = [4, 5, 6]
In [12]: c = [a, b]
In [13]: [j for i in c for j in i]
Out[13]: [1, 2, 3, 4, 5, 6]
Use itertools.chain.
import itertools
a=[1,2,3]
b=[4,5,6]
c = list(itertools.chain(a, b))
You are concatenating, use + to do so:
c = a + b
If you are concatenating an arbitrary number of lists, use itertools.chain.from_iterable():
from itertools import chain
list_of_lists = [a, b]
c = list(chain.from_iterable(list_of_lists))
Note that if all you need to do is iterate over the concatenation result, you can leave of the list() call altogether.
Do not use sum() for this; that leads to quadratic behaviour as intermediate results are built for every element summed, which takes a full loop.
You can do it with + operation
a = [1, 2, 3]
b = [3, 4, 5]
c = a + b # Equal [1, 2, 3, 3, 4, 5]
Here are 3 different ways you can do it:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=a+b
>>> c
[1, 2, 3, 4, 5, 6]
>>> c=[item for l in [a, b] for item in l]
>>> c
[1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain(*[a, b]))
[1, 2, 3, 4, 5, 6]

List of List, want to output variable, not value

I have a list of lists like so:
a = [1, 2, 3]
b = [2, 3, 4]
c = []
append blah blah blah
I currently am doing:
for x in c:
print(x)
and it is outputing [1, 2, 3]. How would i get it to output 'a' instead?
There are a few ways to achieve what you want. The first suggestions require using a different data structure. The last suggestion is for demonstration purposes ONLY and should NEVER BE USED.
Option 1. Store you data in a dictionary:
my_data = {"a": [1, 2, 3], "b": [2, 3, 4]}
my_data["c"] = [my_data.get('a'), my_data.get('b')]
Then you would simply iterate over the key, value pairs.
>>> for name, value in my_data.items():
... print name, value
...
a [1, 2, 3]
c [[1, 2, 3], [2, 3, 4]]
b [2, 3, 4]
The dictionary has no useful ordering, so if you wanted it ordered you could use an OrderedDict, or another data structure like a list of tuples.
Or you could sort them before you iterate:
for name, value in sorted(my_data.items()):
print name, value
You could also create the dictionary after the variables are assigned
>>> a = [1, 2, 3]
>>> b = [2, 3, 4]
>>> c = [a, b]
>>> my_data = {"a": a, "b": b, "c": c}
Option Terrible. The very hackish way to do this (and only for demonstration purposes) is to use locals()
>>> a = [1, 2, 3]
>>> b = [2, 3, 4]
>>> c = [a, b]
>>> for name, value in locals().items():
... if len(name) != 1:
... continue
... print name, value
...
a [1, 2, 3]
c [[1, 2, 3], [2, 3, 4]]
b [2, 3, 4]
You are printing a. Your list c is actually
C = [[1,2,3], [2,3,4]]
If you modify a before printing c. The new values in a will be shown. As python passes by reference and c contains a reference to a
If you want to print the variable name see Can I print original variable's name in Python? and How can you print a variable name in python?
However the answers there say you should not do it.
You are telling it to print the complete contents of c which contains the objects a and b which are indeed
[1, 2, 3]
[2, 3, 4]
You are saying that you want to print the string 'a'
To do that you would have to define
c = ['a', 'b']
which is completely different.

How to create dynamic link between list variables

The dictionary's methods .viewvalues() and .viewkeys() allow to create the list variables that will be linked and dynamically updated on every dictionary modification such as:
diction={'one':1,'two':2,'three':3}
dict_values=dictVar.viewvalues()
dict_keys=dictVar.viewkeys()
I wonder if a similar functionality could be achieved with lists. So if there are two "source" list variables and a third list is a result of sums of twos:
a=[1,2,3]
b=[4,5,6]
sum=a+b
Now what i want is a list variable sum to get updated if/when list variable a or list variable b is modified. How to achieve that?
I'd define a function to do it and then call that whenever you need the list.
a=[1,2,3]
b=[4,5,6]
def sum(a, b):
return a + b
Then, in an interpreter:
>>> sum(a, b)
[1, 2, 3, 4, 5, 6]
>>> a.append(5)
>>> sum(a, b)
[1, 2, 3, 5, 4, 5, 6]
If it's not necessary that it be a flat list, you can easily do what you'd want.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> sum = [a, b]
>>> print(sum)
[[1, 2, 3], [4, 5, 6]]
>>> a.append(8)
>>> print(sum)
[[1, 2, 3, 8], [4, 5, 6]]
That said, I'd recommend against defining a variable named sum as it's a built-in Python function.
You could do it the other way around, using numpy arrays.
>>> import numpy as np
>>> ab = np.array([1,2,3,4,5,6])
>>> a = ab[:3]
>>> b = ab[3:]
>>> a, b
(array([1, 2, 3]), array([4, 5, 6]))
>>> a[1] = 9
>>> ab
array([1, 9, 3, 4, 5, 6])
>>> ab[0] = 7
>>> a
array([7, 9, 3])
Here, a and b are "views" on the array ab, and modifying one will also modify the other.
Starting with a and b, just create a numpy array from a+b and redefine a and b accordingly:
>>> a, b = [1,2,3], [4,5,6]
>>> ab = np.array(a+b)
>>> a, b = ab[:3], ab[3:]
You will have to right a custom data structure to do this. Here is something in the right direction...
class LinkedArrays(object):
def __init__(self, sourceArray1, sourceArray2, combineFunction):
self.sa1, self.sa2 = sourceArray1, sourceArray2
self.__combineFunction = combineFunction
self.__update()
def updateSourceArray1(self, index, value):
self.sa1[index] = value
self.__update()
def updateSourceArray2(self, index, value):
self.sa2[index] = value
self.__update()
def __update(self):
self.combinedArray = [self.__combineFunction(self.sa1[i], self.sa2[i]) for i in range(len(self.sa1))]
def __getitem__(self, item):
return self.combinedArray[item]
summedArrays = LinkedArrays([1, 2, 3], [4, 5, 6], lambda x, y: x+y)
print summedArrays[0] # print 5
summedArrays.updateSourceArray1(0, 6)
print summedArrays[0] # print 10

Python - Declare two variable with the same values at the same time

a=[1,2,3]
b=[1,2,3]
Is there a way to do this on one line? (obviously not with ";")
a,b=[1,2,3]
doesn't work because of
a,b,c=[1,2,3]
a=1
b=2
c=3
In [18]: a,b=[1,2,3],[1,2,3]
In [19]: a
Out[19]: [1, 2, 3]
In [20]: b
Out[20]: [1, 2, 3]
you may also want to do this:
In [22]: a=b=[1,2,3]
In [23]: a
Out[23]: [1, 2, 3]
In [24]: b
Out[24]: [1, 2, 3]
but be careful that, a is b is True in this case, namely, a is just a reference of b
a,b,c = [[1,2,3] for _ in range(3)]
each points to a different object
Edit: as found by DSM in order for the following lines to work you need to declare b as a list in order for my code to work (so this is no longer on one line, but I will leave it here as a reference). Changed the order as suggested by Paulo Bu
a=[1,2,3]
b=a[:]
Old code:
b=[]
a=b[:]=[1,2,3]
This assigns the values to b and then copies all the values from b to a.
If you do it like this:
a=b=[1,2,3]
and then change
b[1] = 0
a would also be changed
>>> a = b = [1, 2, 3]
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> b = [3, 2, 1]
>>> b
[3, 2, 1]
>>> a
[1, 2, 3]
a,b = [1,2,3],[1,2,3] does it in one line and points to different objects.
a=b=[1,2,3] is clear but points to the same object.
Try a.pop(1) in both cases and you will see the difference.
Note... this solution
a=b=[1,2,3]
results in assigning the same (mutable) list to ivar's a and b. The original question shows 2 different lists being assigned to a & b.
This solution suffers the same problem:
>>> a,b = ([1,2,3],)*2
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]

Categories