Python: Assaign values to variables using two lists [duplicate] - python

This question already has answers here:
Convert string to variable name in python [duplicate]
(3 answers)
Closed 7 years ago.
How can I assign values to variables by using two lists:
Numbers =[1,2,3,4,]
Element= ["ElementA","ElementB","ElementC","ElementD"]
for e, n in zip(Element, Numbers):
e+ ' = ' +n #this part is wrong
What i want is a result like this in the end:
print ElementA
>1
print ElementB
>2
print ElementC
>3
print ElementD
>4
So what im trying to do is to fill up variables created from one list (Element) with values from another list (Numbers) in a kind of loop style.
Does anyone know how to archive something like that?
It should also be possible to assign many values contained in a list/array to variables.

Do not do that.
You're already working with lists, so just create a list instead of hacking some hard-coded names. You could use a dictionary if you really wanted to use identifiers like A, B, etc., but you'd have a problem with more than 26 items, and you're just using it to make a sequence anyway. Integers are great for that, and of course we'll start at 0 because that's how it works.
>>> numbers = [1, 2, 3, 4]
>>> elements = [item for item in numbers]
>>> elements[0]
1
And at this point we can see that, for this example at least, you already had what you were looking for this whole time, in numbers.
>>> numbers = [1, 2, 3, 4]
>>> numbers[0]
1
Perfect.

You may use exec but this is generally the wrong way to go.
for e, n in zip(Element, Numbers):
exec(e + ' = ' + n)
You better should use a dictionnary:
my_dict = {}
for e, n in zip(Element, Numbers):
my_dict[e] = n
Even simpler:
my_dict = dict(zip(Element, Numbers))

Related

Python 3: pairwise iterating through list [duplicate]

This question already has answers here:
Iterating over every two elements in a list [duplicate]
(22 answers)
Closed 4 years ago.
I am looking for a nice pythonian solution to read two elements out of a list in Python 3. What do I need to write for ??? in the following code:
it = [1,2,3,4,5,6]
for x, y in ??? :
print (x, y)
The desired output would be:
1 2
3 4
5 6
Also one could solve it with indexed for-loop. But this is also ugly (IMHO)
Use zip(*[iter(it)] * 2), as seen in this answer.
it = [1,2,3,4,5,6]
for x, y in zip(*[iter(it)] * 2):
print(x, y)
Another easy way without zip is:
i = 0
while i < len(it)-1:
print(it[i], it[i+1])
i += 2
Another cheap option, using indices. You might not like them, but they are fast.
it = [1,2,3,4,5,6]
for x in range(0, len(it)-1, 2):
print(it[x], it[x+1])
Here is another approach which will work in Python3:
def pair(a):
# Or simply:
# return zip(a[::2], a[1::2])
for k, v in zip(a[::2], a[1::2]):
yield k, v
a = [1,2,3,4,5,6]
final = list(pair(a))
print(final)
Output:
[(1, 2), (3, 4), (5, 6)]
Got this to work for your case:
l = [1,2,3,4,5,6]
print(*[' '.join([str(a) for a in x]) for x in zip(l[::2],l[1:][::2])],sep='\n')
First I had to use l[::2] to create a list the odd numbers in the list, then l[1:][::2] to get even numbers. Did this using slicing function which is quite useful link
Then I zipped them together to match 1st, 2nd, 3rd elements etc link
Then I used list comprehension to create a list of each of those sets. The problem is that they were sets and not text as above. To resolve this I changed my sets to string str() .
Now that the individual sets have been turned into string, you can join with ' '.
You still have a set of 3 but you can print each line with print(*[list here],sep='\n') link
Learned a few new tricks, hope this helps!

how do you remove a list from another list? [duplicate]

This question already has answers here:
Remove all the elements that occur in one list from another
(13 answers)
Compute list difference [duplicate]
(17 answers)
Closed 6 years ago.
I have something like:
a = [4,3,1,6,3,5,3]
b = [4,2,6]
and I wanted to remove the 3 elements of b from a. I was trying to do:
c = a - b
but I was thinking that the inverse of merge (+) might not be a thing, and was correct: Unsupported Operand types for -: list and list. I was contemplating just looping over them, but that just doesnt really sound pythony.
My end state is going to be: c = [3,1,3,5,3]
If you had not noticed, b is not a subset of a and these are unordered. 2 different sets, these sets are not unique either, but only want to remove 1 instance per i in b, not all instance of i in b
EDIT It seems that the current answer does not resolve my question.
a = [1,1,2,2,2,3,4,5]
b = [1,3]
c = [x for x in a if x not in b]
#c result is [2,2,2,4,5]
I want c to return: [1,2,2,2,4,5]
For the sake of speed typing, I just put sorted numbers, but the lists ARE IN FACT unsorted, though for the sake of cleanliness we can sort them.
They are just unsorted at init. Since there are duplicates in list items, I can't use a set as per the definition of set.
You can use the following code:
[x for x in a if x not in b]
As input and output lists are unordered, use Counter is a way to go:
from collections import Counter
a = [4,3,1,6,3,5,3]
b = [4,2,6]
c = list((Counter(a) - Counter(b)).elements())
print(c)
This solution handles the following case differently than ysearka answer:
a = [4,3,1,6,3,5,3]
b = [3]
Where many answers here leads to c = [4,1,6,5], the one using Counter will outputs c = [4,1,6,3,3,5].
This behavior is also implemented by DAXaholic answer, but with modification of an existing list, which is not a pythonic way to go, and could be costly on big lists.
As you noted you only want to remove the items once per occurrence:
for x in [tmp for tmp in b if tmp in a]:
a.remove(x)
for x in b:
while x in a:
a.remove(x)
Now a is
[3, 1, 3, 5, 3]

PYTHON - creating multiple lists in a loop [duplicate]

This question already has answers here:
How can you dynamically create variables? [duplicate]
(8 answers)
Closed 7 years ago.
I'm trying to put together a programming project at my university, but I'm stuck. The "math" part I've got covered, but I need help with lists and loops in Python.
I'm working with graphs, let me show one example, to make it clearer:
3 node graph
As you can see, I have 3 nodes in it and 2 edges, nothing fancy. I need to compute the closest route between each pair of nodes, and I have that covered already. Now I need to put it either in n lists, n elements each, or in a n x n, so either:
a = [0, 1, 2]
b = [1, 0, 1]
c = [2, 1, 0]
or a table (or matrix?) like this:
table 3x3, where I only really need the part with the white background.
When I read data to work on, I put each node into a list, as a new element, so with these 3 steps I gradually get:
lw = []
lw = ['a']
lw = ['a','b']
lw = ['a','b','c']
Is there any way, to create empty lists out of elemnts of lw? I would really like to name them like dis_a, dis_b, dis_c etc. I tried to do it with a dictionary, but then I couldn't manipulate with those lists, like I usually do. And truth be told, I'd much prefer the solution using lists, as I already have a latter part of the program written for this.
EDIT:
Ok, so one of you asked for input/output to make my question clearer. Mmy input is:
lw = ['a','b','c']
my desired output is:
a = []
b = []
c = []
or something like that (lists that can be easly identified with the nodes, that I have listed in lw)
EDIT2:
Ok, so now I have a number of lists created like this (still sticking to the example):
dis['a']
dis['b']
dis['c']
I have a working command
path[X][Y]
which on input takes the names of the nodes (as in lw list ex. 'a'), and on input returns a list of
nodes on the shortest path from X to Y. What I need to be doing now, is to take the length of it with
len(path[X][Y])
And substract 1 from it (it's counting the "starting" point as well, so it's correcting it). Then I have
to put this number in a corresponding place in a list. I would like to do it in a loop, so it would
automatically append numbers to existing lists, so I would automatically get from
dis['a'] = []
dis['b'] = []
dis['c'] = []
to
dis['a'] = [0, 1, 2]
dis['b'] = [1, 0, 1]
dis['c'] = [2, 1, 0]
Don't worry, about it calculating the path twice (ex. from a to b and then from b to a), It doesn't have to be perfect ;) I tried to create such method, but I have no idea, how to store the results in said lists (or if I'm even correct). Here is my proposition:
def lo():
for i in range(0, len(lw)):
for j in range (0, len(lw)):
dis[i].append(path[lw[i]][lw[j]])
What couldn't you manipulate with a dictionary?
dis_a, dis_b, dis_c... could as well be dis['a'], dis['b'] and dis['c']...
You could do:
dis = {}
for elem in lw:
dis[elem] = []
# ...
Want to loop over all dis-es now?
for elem, val in dis.iteritems():
print elem # your a, b, or c
print val # your [] corresponding to a, b, or c
If you want to add elements, and find min and max (as requested in the comments):
Let's say initially dis['a'] gets [0, 1, 2]
and ...
dis['b'] = [1, 0, 1]
dis['c'] = [2, 1, 0]
and now you want to add a new item to all of the dis-es...
item = 5
for elem in dis:
dis[elem].append(item)
and now you want to find the max ...
for elem in dis:
print max(dis[elem])
If I'm correct you want to dynamically create variables.
Here is short answer, for more information checkout this post How can you dynamically create variables via a while loop? Actually there you can find different approaches like using a dict.
>>> lw = ['a', 'b', 'c']
>>> for l in lw:
exec("{prefix}{var}=[]".format(prefix="dis_", var=l))
>>> dis_a
[]
>>> dis_b.append('some')
>>> dis_b
['some']

Python lists get specific length of elements from index [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 9 years ago.
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
I need to obtain a specific length of elements form a list starting at a specific index in Python. For instance I would like to get the three next elements from the [2] element above. Is there anyway to get the three elements from the specific index? I wont always know the next amount of elements I want to get, sometimes I may want to get two elements, sometimes eight elements, so x elements.
I know I can do my_list[2:] to get all of the elements from the third element to the end of the list. What I want to do is specify how many elements to read after the third element. Conceptually in my mind the example above would look like my_list[2:+3] however I know this wont work.
How can I achieve this or is it better to define my own function to give me this functionality?
You are actually very close:
>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> x = 3
>>> my_list[2:2+x]
[3, 4, 5]
>>>
As you can see, the answer to your question is to slice the list.
The syntax for slicing is list[start:stop:step]. start is where to begin, stop is where to end, and step is what to count by (I didn't use step in my answer).
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
n = 3
print my_list[2:2+n]
Nothing smart here. But, you can pull n out and tweak it the way you want.
you should simply use
my_list[2:2+3]
and in general
list[ STARTING_INDEX : END_INDEX ]
which is equivalent to
list[ STARTING_INDEX : STARTING_INDEX + LENGTH ]
>>> my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13]
>>> my_list[2:3]
[3]
>>> my_list[2:2+3]
[3, 4, 5]

Python unique list using set [duplicate]

This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(31 answers)
Closed 8 months ago.
What I am trying to do is write a method that takes a list as an argument and uses a set to return a copy of the list where each element only occurs once, as well as having the elements in the new list occur in order of their first occurrence in the original list. I HAVE to use a set for this, however, I can't make it so that the output is in the right order while having a quick result.
If I put something like this:
def unique(a):
return list(set(a))
and passed a list with millions of elements, it would give me a result quickly, but it wouldn't be ordered.
So what I have right now is this:
def unique(a):
b = set(a)
c = {}
d = []
for i in b:
c[a.index(i)] = i
for i in c:
d.append(c[i])
return d
This gives me the result I want, but not fast enough. If I pass a list with a million elements, I could be waiting for half an hour, whereas the one liner up there takes less than a second. How could I solve this problem?
>>> from collections import OrderedDict
>>> items = [1, 2, 3, 'a', 2, 4, 'a']
>>> OrderedDict.fromkeys(items).keys()
[1, 2, 3, 'a', 4]

Categories