Piecewise list comprehensions in python
What is the easiest/most elegant way to do the following in python:
def piecewiseProperty(aList):
result = []
valueTrue = 50
valueFalse = 10
for x in aList:
if hasProperty(x):
result.append(valueTrue)
else
result.append(valueFalse)
return result
where hasProperty
is some function with boolean 开发者_如何学运维return value.
One shorter (but opaque, and possibly less efficient) R-like way to do it would be this
trueIndexSet = set([ ind for ind,x in enumerate(aList) if hasProperty(x) ])
falseIndexSet = set(range(0:len(aList)).difference(trueIndexSet)
vals = sorted( [ (ind,10) for ind in falseIndexSet ] + [ (ind,50) for ind in trueIndexSet ] )
[ x for ind,x in vals]
Another much tidier approach would use dictionary lookup:
[ {True:50, False:10}[hasProperty(x)] for x in aList ]
Is there some clever and readable one-liner or built in function for doing this? It would basically be an if...else list comprehension.
Application of this question: Just in case it's of interest, I am using this to assign sizes to nodes in a network so that they are drawn differently. I want to draw nodes named with prefix "small_" size 10 and draw the other nodes size 50. NetworkX and pygraphviz can alter the sizes of the nodes by accepting a list of sizes, one for each node.
Use a conditional expression (pep-308):
[50 if hasProperty(x) else 10 for x in alist]
How about:
[50 if hasProperty(x) else 10 for x in aList]
?
精彩评论