[英]How do you access specific elements from the nested lists
我正在嘗試訪問嵌套列表中的元素。 例如,
file = [[“Name”,”Age”,”Medal”,”Location”],[“Jack”,”31”,”Gold”,”China”],[“Jim”,”29”,”Silver”,”US”]]
此數據至少包含 3000 個列表。 我只想將數據放入一個包含名稱和“位置”列的新列表中
Output 應該是: [[“Name”,”Location”],[“Jack”,”China”],[“Jim”,”US”]]
這看起來像一個數據框。 但是我不能使用任何模塊來分隔列。 我如何使用 python 內置 function 和方法對其進行編碼。 我嘗試了循環但失敗了,
這是一個列表理解問題:
newfile = [row[0:2] for row in file]
您可以通過切片數組來完成此操作。 見下文:
newArr = [r[0:2] for r in oldArr]
如果我們有任何順序數據類型,如lists, strings, tuples, bytes, bytearrays, and ranges
,那么 Python 支持切片表示法,我們可以使用 for 循環遍歷給定列表中的每個字符。
如果我們有一個二維或嵌套列表,那么
file = [["Name","Age","Medal","Location"],["Jack","31","Gold","China"],["Jim","29","Silver","US"]]
for r in file:
print(r)
OUTPUT:-
['Name', 'Age', 'Medal', 'Location']
['Jack', '31', 'Gold', 'China']
['Jim', '29', 'Silver', 'US']
# ----------------------------------------------------------------
# if we want only specific elements
# then we use the slicing method
# ----------------------------------------------------------------
for r in file:
print(r[0:2])
OUTPUT:-
['Name', 'Age']
['Jack', '31']
['Jim', '29']
# ----------------------------------------------------------------
# if we want to output as a list
# then we can use single line for loop
# ----------------------------------------------------------------
newFile = [r for r in file]
print(newFile)
OUTPUT:
[['Name', 'Age', 'Medal', 'Location'], ['Jack', '31', 'Gold', 'China'], ['Jim', '29', 'Silver', 'US']]
# ----------------------------------------------------------------
# Output should be: [[“Name”,”Age”],[“Jack”,”31”],[“Jim”,”29”]]
# ----------------------------------------------------------------
newFile = [r[0:2] for r in file]
print(newFile)
OUTPUT:
[['Name', 'Age'], ['Jack', '31'], ['Jim', '29']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.