This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
I have a list of variables in Python:
a = 1
b = 0
c = 0
These come from part of a script that gets user input for certain fields to process, so 1 means "do something to 'a'" and 0 means "do not include." So it would be useful to know which fields need to be used later in the script, i.e. which of them equal 1.
What's the best way to find which of a, b or c is equal to 1?
I tried this method (from here):
test_list = [a,b,c]
next((x for x in test_list if x == 1), None)
Which returns 1, but I'm looking for it to return a. This is precondition, the next step in the script takes the variables that equal 1 and does something with them, by variable name rather than value.
I could do it long-hand like this:
if a == 1:
print "a"
if b == 1:
...
but I suspect there's a nice Pythonic way to find the name of a variable from a list of variables that equals a specific value.
You should consider using a dictionary (a mapping) instead of a list, as names only reference objects but are not the objects themselves:
d = dict(a = 1, b = 2, c = 0)
print(next((k for k, v in d.items() if v == 1), None))
# a
Related
This question already has answers here:
Python: determining whether any item in sequence is equal to any other
(5 answers)
Closed 3 years ago.
I have three integers, and I need to check if two of them are equal. The code I have is quite ugly:
a = 5
b = 7
c = 5
if a == b or b == c or a == b:
pass
I wonder if there is a better alternative to this kind of comparation.
You could just build a set and check the resulting length:
a = 5
b = 7
c = 5
if len({a,b,c}) < 3:
pass
Since you mention in your real case the variables are lists, you could convert them to tuples which are hashable and hence can build a set from them. So instead you could do:
a = [5, 2]
b = [7, 2]
c = [5, 2]
if len(set(map(tuple, [a,b,c]))) < 3:
pass
Because you are having lists, you won't be able to use a set directly. If so, you will get an error:
TypeError: unhashable type: 'list'
Convert your lists to tuples, then use the following:
if len(set([tuple(a),tuple(b), tuple(c)])) < 3:
pass
This question already has answers here:
How does a for loop evaluate its argument
(3 answers)
Closed 6 years ago.
counter = Counter()
// fill data into counter
for a, b in counter.most_common():
if (b > 1):
counter[a] = np.log(b)
else:
counter[a] = -np.log((1 / (b+0.01)))
As I see, this is safe, based on my trial. No bad thing happens when I change the collection while I am enumerating it. In other languages, in each cycle of the for, the counter.most_common() value is evaluated.
Doesn't this happen in Python as well?
No, it doesn't. A more illustrative example:
def example():
print("Ping")
return [1,2,3,4]
for x in example():
print(x)
Output:
Ping
1
2
3
4
This question already has answers here:
What is a None value?
(9 answers)
Is there a difference between "==" and "is"?
(13 answers)
Closed 6 years ago.
I think [None] is same as [], but in my test , maybe there is something...
>>>print len([])
0
>>>print len([None])
1
when should i use the None ? and []
and another interesting question
>>>c= []
>>>d= []
>>>print c is d
False
>>>a= 1
>>>b=1
print a is b
True
why empty list's id granting that is different?
[] is an empty list
[None] is a list with one element. That one element is None
is checks for reference equality. If both objects refer to the same object by reference then is will return true.
a = []
b = a
a is [] #false
a is b #true
[None] does not mean that there is nothing in the list. None is a keyword in python which has a special meaning. It is like NIL or NULL in other languages.
When you say [None], you are saying "I would like to have a list which contains the special object called None". This is different than saying "I would like a list which contains no elements" (by typing []).
Question 1:
None is an object. It is of type "NoneType".
This can be seen by doing something like this in the terminal:
>>> type(None)
<type 'NoneType'>
So, when you put this object in a list, the list has one element.
Question 2:
The assignment operator in Python, =, is used to attach a name to an object. In the case of immutable objects, like integers, multiple names can be attached to the same object. That is what you are doing with a and b. So, when you test their identity, using the is operator, you see that the two names point to the identical object.
Alternatively, when you attach a name to a newly created list (which you created with the [] operator) it is a different list each time.
None is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None.
For (equality) comparisons you shouldn't use is. Use ==!
Because is can lead to strange behaviour if you don't know exactly when and how to use it. For example:
>>> 1900 is 1900
True
>>> a = 1900
>>> b = 1900
>>> a is b
False
>>> a, b = 1900, 1900
>>> a is b
True
This rather strange behaviour is explained for example in this question: Why does Python handle '1 is 1**2' differently from '1000 is 10**3'?
This won't happen when you use ==:
>>> a == b
True
>>> 1900 == 1900
True
like one would expect.
You want to use None to imply that there is no valid object. You want to use [] to imply an object that is of type list and has no elements.
[None] is a list with one element which is None
>>>c= [] # This is a new list object
>>>d= [] # This is another new list object
In Python , x is y is used to check whether x and y are the same objects.
Here, c and d point to different list objects.
so,
>>>print c is d
False
is expected.
On the other hand,
>>>c= [] # This is a new list object
>>>d = c # This is the same object as c
>>>print c is d
True
Here, a and b are primitives, not objects
>>>a= 1
>>>b=1
So, this is expected:
print a is b
True
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4