The "brackets" in your example constructs a new list from an old one, this is called list comprehension.
The basic idea with [f(x) for x in xs if condition] is:
def list_comprehension(xs):
result = []
for x in xs:
if condition:
result.append(f(x))
return result
The f(x) can be any expression, containing x or not.
The "brackets" in your example constructs a new list from an old one, this is called list comprehension.
The basic idea with [f(x) for x in xs if condition] is:
def list_comprehension(xs):
result = []
for x in xs:
if condition:
result.append(f(x))
return result
The f(x) can be any expression, containing x or not.
That's a list comprehension, a neat way of creating lists with certain conditions on the fly.
You can make it a short form of this:
a = []
for record in records.split("\n"):
if record.strip() != '':
a.append(record)
for record in a:
# do something
They're both List comprehensions in python
The closest you can get to a list comprehension in python in Javascript (Without ES6, babel and its relations) is to use Array.Map (Similar to python's map)
Example in python
>>> l = [2, 4, 6, 8, 10, 12]
>>> [int(i / 2) for i in l]
[1, 2, 3, 4, 5, 6]
In Javascript:
l = [2, 4, 6, 8, 10, 12]
l.map(function(i){ return i / 2 });
[1, 2, 3, 4, 5, 6]
With Arrow functions in ES6, you can get rid of the function(){}
l.map(x => x/2)
[2, 4, 6, 8, 10, 12]
So your code should look like this
const p_new = p.map(function(i){ if(i in N(vertex)){ return i } });
const x_new = x.map(function(i){ if(i in N(vertex)){ return i } });
It would be better to use:
p.filter(val => graph[vertex][val])
As this cuts out the useless Array creation that N does.
Also ~~ doesn't properly convert -1 to false and 0 .. n to true. Use !!~ instead.
Videos
When you do this:
>>> myList = [[99]]
>>> for x in myList:
print x
Python interprets that as "print each element in this iterable".
When you do this:
>>> myList = [[99,100], [99,101], [99, 102]]
>>> for x in myList:
print x
Python still interprets that as "print each element in this iterable" so that you get this:
[99, 100]
[99, 101]
[99, 102]
But, if you do this:
>>> myList = [[99,100], [99,101], [99, 102]]
>>> for x, y in myList:
print x, y
Python will "unpack" the values for you from each element in the iterable and assign them to x and y. If you want to do that above for only the case of myList = [[99]], Python requires the for [x] in myList syntax so that it unpacks the single value from the list.
The ability to "unpack" an iterable is very powerful in Python. You can assign variables on the fly by unpacking an iterable. In your case, you can imagine having to assign lat lon as variables maybe or something else. You can also unpack values into the args of a function.
In Python 3 you can also do something like this:
x = [1,2,3,4]
first, *rest = x
print (first) # 1
print (rest) # [2,3,4]
For the second example, with lists of length 2, to unpack both values you can do
In[1]:
myList = [[99,100]]
for x, y in myList:
print(x)
print(y)
Out[1]:
99
100
[str(wi) for wi in wordids]
is a list comprehension.
a = [str(wi) for wi in wordids]
is the same as
a = []
for wi in wordids:
a.append(str(wi))
So
createkey='_'.join(sorted([str(wi) for wi in wordids]))
creates a list of strings from each item in wordids, then sorts that list and joins it into a big string using _ as a separator.
As agf rightly noted, you can also use a generator expression, which looks just like a list comprehension but with parentheses instead of brackets. This avoids construction of a list if you don't need it later (except for iterating over it). And if you already have parentheses there like in this case with sorted(...) you can simply remove the brackets.
However, in this special case you won't be getting a performance benefit (in fact, it'll be about 10 % slower; I timed it) because sorted() will need to build a list anyway, but it looks a bit nicer:
createkey='_'.join(sorted(str(wi) for wi in wordids))
normalizedscores = dict([(u,float(l)/maxscore) for (u,l) in linkscores.items()])
iterates through the items of the dictionary linkscores, where each item is a key/value pair. It creates a list of key/l/maxscore tuples and then turns that list back into a dictionary.
However, since Python 2.7, you could also use dict comprehensions:
normalizedscores = {u:float(l)/maxscore for (u,l) in linkscores.items()}
Here's some timing data:
Python 3.2.2
>>> import timeit
>>> timeit.timeit(stmt="a = '_'.join(sorted([str(x) for x in n]))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
61.37724242267409
>>> timeit.timeit(stmt="a = '_'.join(sorted(str(x) for x in n))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
66.01814811313774
Python 2.7.2
>>> import timeit
>>> timeit.timeit(stmt="a = '_'.join(sorted([str(x) for x in n]))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
58.01728623923137
>>> timeit.timeit(stmt="a = '_'.join(sorted(str(x) for x in n))", setup="import random; n = [random.randint(0,1000) for i in range(100)]")
60.58927580777687
Let's take the first one:
str(wi) for wi in wordidstakes each element inwordidsand converts it to string.sorted(...)sorts them (lexicographically).'_'.join(...)merges the sorted word ids into a single string with underscores between entries.
Now the second one:
normalizedscores = dict([(u,float(1)/maxscore) for (u,l) in linkscores.items()])
linkscoresis a dictionary (or a dictionary-like object).for (u,l) in linkscores.items()iterates over all entries in the dictionary, for each entry assigning the key and the value touandl.(u,float(1)/maxscore)is a tuple, the first element of which isuand the second element is1/maxscore(to me, this looks like it might be a typo:float(l)/maxscorewould make more sense -- note the lowercase letter el in place of one).dict(...)constructs a dictionary from the list of tuples, where the first element of each tuple is taken as the key and the second is taken as the value.
In short, it makes a copy of the dictionary, preserving the keys and dividing each value by maxscore.
I'm looking at a sample piece of code and I see this bit of logic:
for i in range(6,10)[::-1]:
I know what "for i in range(6,10)" does, and [::-1] looks like some sort of slicing, but I've never seen it used in this context. What is this doing, exactly?
I am trying to understand this code. I understand that first for loop is iterating over the comments using the message column. However, why is a second for loop required and what do the curly braces do?
for comment in comments[' Message']:
s = sentiment.polarity_scores(comment)
for k in sorted(s):
print('{0}: {1}, '.format(k,s[k]))
print(comment)Your code, as written, is close:
opnDays = ["mon", "tue", "wed", "thr", "fri"]
price = 10
def discount(array):
disPrice = price
for day in array:
disPrice *= 0.9
print(day, disPrice)
What I did here was change how disPrice was set on your loop. You were setting it to the same value (0.9 * price) on every iteration. All I did was set it to price in the beginning and multiply it by 0.9 every iteration, resulting in the desired behavior.
You're not changing the value of price so the same result is calculated on every iteration of the loop.
This should work:
for day in array:
price = price - (price * .1)
print(day, price)