# 9個都要了解的單行Python代碼

### 1. If — Else 語句

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

``````age = 18
invalid = "You're NOT an adult"
print(valid) if age >= 18 else print(invalid)
``````

### 2. 根據現有列表創建新列表

``````[expression for item in list]
``````

``````words = ['united states', 'brazil', 'united kingdom']

capitalized = [word.title() for word in words]
>>> capitalized
['United States', 'Brazil', 'United Kingdom']
``````

### 3. 字典推導

``````{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}
``````

### 4. 合併詞典

``````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}
``````

### 5.刪除列表中的重複項

set是一種無序集合，其中每個元素都是唯一的。這意味着如果我們將列表變成一個集合，就可以快速刪除重複項，。然後我們只需要將集合再次轉換爲列表即可。

``````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]
``````

### 6. 在一行中給多個變量賦值

``````a, b, c = 1, "abc",  True
>>> a
1
>>> b
'abc'
>>> c
True
``````

### 7. 從列表中過濾值

``````filter(function, iterable)
``````

``````#學習中遇到問題沒人解答？小編創建了一個Python學習交流羣：725638078
my_list = [10, 11, 12, 13, 14, 15]
>>> list(filter(lambda x: x%2 == 0, my_list ))
[10, 12, 14]
``````

### 8. 按鍵排序字典

``````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}
``````

### 9. 按值排序字典

``````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}
``````