9個應知應會的單行Python程式碼

1. If — Else 語句

if-else 語句是我們在 Python 中學習的第一批語句之一,它用於執行給定條件的真假部分。

age = 18
valid = "You're an adult"
invalid = "You're NOT an adult"
print(valid) if age >= 18 else print(invalid)
[expression for item in list]
words = ['united states', 'brazil', 'united kingdom']

capitalized = [word.title() for word in words]
>>> capitalized
['United States', 'Brazil', 'United Kingdom']
{key: value for key, value in iterable}
dict_numbers = {x:x*x for x in range(1,6) }
>>> dict_numbers
{1: 1, 2: 4, 3: 9, 4: 16, 5:25}
dict_1 = {'a': 1, 'b': 2}
dict_2 = {'c': 3, 'd': 4}
merged_dict = {**dict_1, **dict_2}
>>> merged_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
numbers = [1,1,1,2,2,3,4,5,6,7,7,8,9,9,9]

>>> list(set(numbers))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
a, b, c = 1, "abc",  True
>>> a
1
>>> b
'abc'
>>> c
True
filter(function, iterable)
my_list = [10, 11, 12, 13, 14, 15]
>>> list(filter(lambda x: x%2 == 0, my_list ))
[10, 12, 14]
product_prices = {'Z': 9.99, 'Y': 9.99, 'X': 9.99}
>>{key:product_prices[key] for key in sorted(product_prices.keys())}
{'X': 9.99, 'Y': 9.99, 'Z': 9.99}
sorted(iterable, key=None, reverse=False)
population = {'USA':329.5, 'Brazil': 212.6, 'UK': 67.2}

>>> sorted(population.items(), key=lambda x:x[1])
[('UK', 67.2), ('Brazil', 212.6), ('USA', 329.5)]
population = {'USA':329.5, 'Brazil': 212.6, 'UK': 67.2}

>>> {k:v for k, v in sorted(population.items(), key=lambda x:x[1])}
{'UK': 67.2, 'Brazil': 212.6, 'USA': 329.5}

文章推薦

餅圖變形記,肝了3000字,收藏就是學會!

--

--

這是一個專注於數據分析職場的內容部落格,聚焦一批數據分析愛好者,在這裡,我會分享數據分析相關知識點推送、(工具/書籍)等推薦、職場心得、熱點資訊剖析以及資源大盤點,希望同樣熱愛數據的我們一同進步! 臉書會有更多互動喔:https://www.facebook.com/shujvfenxi/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
數據分析那些事

數據分析那些事

這是一個專注於數據分析職場的內容部落格,聚焦一批數據分析愛好者,在這裡,我會分享數據分析相關知識點推送、(工具/書籍)等推薦、職場心得、熱點資訊剖析以及資源大盤點,希望同樣熱愛數據的我們一同進步! 臉書會有更多互動喔:https://www.facebook.com/shujvfenxi/