Python - Assign None or value - python-2.7

Is there a short way to assign None or value in a variable, depending on the value?
x= value if value!= 999 else None

result = (on_false, on_true)[condition]
>>> value = 10
>>> x = (None,value)[value != 999]
>>> print x
10
>>> value = 999
>>> x = (None,value)[value != 999]
>>> print x
None

You are using the correct way to do it.
but if you insist on shorten way to figure it out you can use this method:
first way:
{0:value}.get(value==999)
using the trick python saving same hash for False and 0 (hash = 0).
second way:
{999:None}.get(value,value)
using get method and default value to bring this.
third way:
[None, value][value != 999]
when first part stand for value declaration and the second as boolean condition.

Related

how to convert 123456,123456,B-CAT to '123456','123456','B-CAT' in python

By using this query
SELECT GROUP_CONCAT(ProductID) FROM blog_txstock
WHERE LastUpdateOn BETWEEN ('2016-05-01 00:00:00') AND ('2016-05-09 00:00:00');
I am getting the result like
123456,123456,B-CAT
but i want to convert that result in to
'123456','123456','B-CAT'
You just need to change the outer quotes:
>>> s = '123456,123456,B-CAT'
>>> ",".join("'{0}'".format(i) for i in s.split(','))
"'123456','123456','B-CAT'"
In case you are wondering why its showing with an extra " " that's just the way its represented, if you save the resulting value and print it, you will get the result you want.
>>> r = ",".join("'{0}'".format(i) for i in s.split(','))
>>> print(r)
'123456','123456','B-CAT'

Get dictionary with lowest key value from a list of dictionaries

From a list of dictionaries I would like to get the dictionary with the lowest value for the 'cost' key and then remove the other key,value pairs from that dictionary
lst = [{'probability': '0.44076116', 'cost': '108.41'} , {'probability': '0.55923884', 'cost': '76.56'}]
You can supply a custom key function to the min() built-in function:
>>> min(lst, key=lambda item: float(item['cost']))
{'cost': '76.56', 'probability': '0.55923884'}
Or, if you just need a minimum cost value itself, you can find a minimum cost value from the list of cost values:
costs = [float(item["cost"]) for item in lst]
print(min(costs))
#alecxe's solution is neat and short, +1 for him. here's my way to do it:
>>> dict_to_keep = dict()
>>> min=1000000
>>> for d in lst:
... if float(d["cost"]) < min:
... min = float(d["cost"])
... dict_to_keep = d
...
>>> print (dict_to_keep)
{'cost': '76.56', 'probability': '0.55923884'}

Subset a list of tuples by max value in Python

My question arise from this discussion. I apologize, but I was not able to add a comment to ask my question under another answer because of my level. I have this list of tuples:
my_list = [('Scaffold100019', 98310), ('Scaffold100019', 14807), ('Scaffold100425', 197577), ('Scaffold100636', 326), ('Scaffold10064', 85415), ('Scaffold10064', 94518)]
I would like to make a dictionary which stores only the max value for each key defined as the first element of the tuple:
my_dict = {'Scaffold100019': 98310, 'Scaffold100425': 197577, 'Scaffold100636': 326, 'Scaffold10064': 94518}
Starting from the Marcus Müller's answer I have:
d = {}
#build a dictionary of lists
for x,y in my_list: d.setdefault(x,[]).append(y)
my_dict = {}
#build a dictionary with the max value only
for item in d: my_dict[item] = max(d[item])
In this way I reach my goal but, is there a sleeker way to complete this task?
I suggest this solution with only one loop, quite readable:
my_dict = {}
for x,y in my_list:
if x in my_dict.keys():
my_dict [x] = max (y, my_dict [x])
else:
my_dict [x] = y
You could use collections.defaultdict.
from collections import defaultdict
d = defaultdict(int)
for key, value in my_list:
d[key] = max(d[key], value)
The above code works on your example data, but will only work in general if each key has a maximum value that is nonnegative. This is because defaultdict(int) returns zero when no value is set, so if all values for a given key are negative, the resulting max will incorrectly be zero.
If purely negative values are possible for a given key, you can make the following alteration:
d = defaultdict(lambda: -float('inf'))
With this alteration, negative infinity will be returned when a key isn't set, so negative values are no longer a concern.
Use the fact that everything is greater than None and the dictionaries get method with None as the fallback return value.
>>> d = {}
>>> for name, value in my_list:
... if value > d.get(name, None):
... d[name] = value
...
>>> d
{'Scaffold100425': 197577, 'Scaffold10064': 94518, 'Scaffold100019': 98310, 'Scaffold100636': 326}
This will work for all values and hashes at most two times per loop.

How to check if a number comes before another in a List

How can I go about checking if an element comes before another in a list?
For example:
how can I check if 5 comes before 12 in a list:
li = [1,2,3,7,4,5,10,8,9,12,11]
Is there an built-in Python function that can allow me to do that?
Here ya go:
>>> li = [1,2,3,7,4,5,10,8,9,12,11]
>>> li.index(5) > li.index(12) # 5 comes after 12
False
>>> li.index(5) < li.index(12) # 5 comes before 12
True
>>>
>>> help(list.index)
Help on method_descriptor:
index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
>>>
if li.index(5) < li.index(12):
print "came before"
You can use list's inbuilt index function:
>>> l = [1,2,3,7,3,5,21,8,44,16,12]
>>> l.index(5) > l.index(12)
False
>>> l.index(5) < l.index(12)
True
>>>
index returns the index of the first occurrence of a number. An example of how index works:
>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.index(0)
0
Note that there are two 0s here.
I don't know python, but generally arrays and lists in programming languages use a zero-based index to identify each element. You usually can access each element via their index in the using the format li[index] = element. For example:
let li = [1,2,3,7,4,5,10,8,9,12,11]
li[0] = 1;
li[1] = 2;
li[2] = 3;
li[3] = 7;
li[4] = 4;
etc. Many systems will also have an IndexOf() method that will allow you to determine the index of an element using a format similar to li.IndexOf(element). This feature can be used in your example such as:
Boolean Is_5_B4_12 = li.IndexOf(5) < li.IndexOf(12);
If python does not have such a feature, you can easily create one yourself by using a loop and an incrementor. Something similar to this would work:
Function IndexOf(integer element)
integer index = 0;
Do While index < len(li) //len() is a function that specifies the number of elements in the list
if li[index] == element then return index;
index = index + 1;
Loop
End Function
I hope this answers your question! Regards - yisrael lax

Adding multiple elements in a list to list.count (Python)

Apologies for the somewhat vague title, I'll try explain more here.
Currently, I have the following code, which counts the number of times the values "y" and "n" show up in the list called "results".
NumberOfA = results.count("y")
NumberOfB = results.count("n")
Is there a way of making it so that, for example, values such as "yes" are also counted towards NumberOfA? I was thinking something along the lines of the following:
NumberOfA = results.count("y" and "yes" and "Yes")
NumberOfB = results.count("n" and "no" and "No")
But that doesn't work. This is probably a pretty easy one to solve, but hey. Thanks in advance!
As for why your answer above does not work, it is because Python will just take the final value of the expression you pass in:
>>> 'Yes' and 'y' and 'yes'
'yes'
Therefore your count will be off because it is just looking for that final value:
>>> results.count('yes' and 'y')
1
>>> results.count('yes' and '???')
0
Would something like this work? Note that this depends on their being only yes/no-esque answers in the list (will be wrong if things like 'Yeah....um no' are in there):
In [1]: results = ['yes', 'y', 'Yes', 'no', 'NO', 'n']
In [2]: yes = sum(1 for x in results if x.lower().startswith('y'))
In [3]: no = sum(1 for x in results if x.lower().startswith('n'))
In [4]: print yes, no
3 3
The general idea is to take your results list and then iterate through each item, lowercasing it and then taking the first letter (startswith) - if the letter is a y, we know it is a yes; otherwise, it will be no.
You can also combine the steps above if you want by doing something like this (note this requires Python 2.7):
>>> from collections import Counter
>>> results = ['yes', 'y', 'Yes', 'no', 'NO', 'n']
>>> Counter((x.lower()[0] for x in results))
Counter({'y': 3, 'n': 3})
Counter objects can be treated just like dictionaries, so you would now essentially have a dictionary that contained the counts of yes's and no's.
NumberOfA = results.count("y") + results.count("yes") + results.count("Yes")
NumberOfB = results.count("n") + results.count("no") + results.count("No")
Create a method
def multiCount(lstToCount, lstToLookFor):
total = 0
for toLookFor in lstToLookFor:
total = total + lstToCount.count(toLookFor)
return total
Then
NumberOfA = multiCount(results, ["y", "yes", "Yes"])
NumberOfB = multiCount(results, ["n", "no", "No"])