在Python元组列表中选择具体值
當需要在元組列表中找出具體值時,可以使用「字典」方法、「獲取」方法和列表解析式。
列表解析式是一種縮寫方式,用於遍歷列表並執行操作。可以使用列表儲存異質值(即任何資料類型,例如整數、浮點數、字串等等)。
元組列表基本上包含的是用列表框住的元組。
「字典」方法會建立一個字典。其中包含關鍵值對,它們是無序且已編制索引的。
「獲取」方法會在字典裡找到特定鍵時,傳回該鍵的值。
以下是一個相關示範:
範例
my_list_1 = [('Jane', 11), ('Nick', 12), ('Will', 33), ('Paul', 14)]
my_list_2 = ['Nick', 'Paul']
print ("The list of tuple is : ")
print(my_list_1)
print ("The second list is : ")
print(my_list_2)
temp_val = dict(my_list_1)
my_result = [temp_val.get(i, 0) for i in my_list_2]
print ("The selective values of the keys are : ")
print(my_result)輸出
The list of tuple is :
[('Jane', 11), ('Nick', 12), ('Will', 33), ('Paul', 14)]
The second list is :
['Nick', 'Paul']
The selective values of the keys are :
[12, 14]說明
- 定義了一個元組列表並顯示在控制台上。
- 定義了另一個清單。
- 從元組列表建立字典。
- 可用於遍歷其他清單。
- 此值被指定給另一個變數。
- 此變數以輸出形式顯示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP