有人可以向我解釋爲什麼這兩個語句(for循環和理解)返回兩個不同的答案。我認爲他們是一樣的,只是不同的寫作方式。python for循環和理解循環
使用的數據:
Top152['% Renewable']
Country
China 19.754910
United States 11.570980
Japan 10.232820
United Kingdom 10.600470
Russian Federation 17.288680
Canada 61.945430
Germany 17.901530
India 14.969080
France 17.020280
South Korea 2.279353
Italy 33.667230
Spain 37.968590
Iran 5.707721
Australia 11.810810
Brazil 69.648030
For循環:
def answer_ten():
Top15 = answer_one()
Top152 = Top15.copy()
for x in Top152['% Renewable']:
if x >= Top152['% Renewable'].median():
Top152['HighRenew'] = 1
else:
Top152['HighRenew'] = 0
return Top152['HighRenew']
answer_ten()
輸出:
Country
China 1
United States 1
Japan 1
United Kingdom 1
Russian Federation 1
Canada 1
Germany 1
India 1
France 1
South Korea 1
Italy 1
Spain 1
Iran 1
Australia 1
Brazil 1
理解:
def answer_ten():
Top15 = answer_one()
Top152 = Top15.copy()
Top152['HighRenew'] = [1 if x >= Top152['% Renewable'].median() else 0 for x in Top152['% Renewable']]
return Top152['HighRenew']
answer_ten()
輸出:
Country
China 1
United States 0
Japan 0
United Kingdom 0
Russian Federation 1
Canada 1
Germany 1
India 0
France 1
South Korea 0
Italy 1
Spain 1
Iran 0
Australia 0
Brazil 1