[英]Processing 2D Array into a List of Lists in Python
我想處理這個二維數組('more')以獲得列表列表('rm'),以便最終結果如下所示:
Month1 Month2 Month3
rm = [[3, [4], [5]]
2,
1,
0],
其中“更多”的第一列對應於車站數據收集的月份。 在刪除 -999 值之后,上面的最終 output 有 3 個列表,分別用於 3 個月的數據收集。 請注意,在原始數組中,一個月的數據可能會分布到幾行,但它們最終都會在最終 output 中的一個列表中結束。
我是 python 的新手,所以我知道我沒有很好地正確構建這個框架。 感謝您在這方面的幫助。
rm = []
Month Station1 Station2 Station3
more = [[1, -999, 3, 2],
[1, 1, 0, -999],
[2, 4, -999, -999],
[3, -999, -999, 5]]
for i in range(0, len(more)):
rm.append([])
r = 0
for j in range(1, len(more[0])):
col = more[i][0] - 1
if (more[i][j] > -999):
rm[r][col].append(more[i][j])
r = r + 1
print(rm)
使用此代碼,我收到以下行的錯誤“列表索引超出范圍”:
rm[r][col].append(more[i][j])
謝謝 !
您正在嘗試獲取沒有任何索引值的空列表的索引。 rm[r][col]
將訪問 rm 的 0 索引,然后嘗試訪問您附加的列表的 0 索引,該列表為空且沒有索引。 我認為字典最好不要附加到列表中,以更有條理地保存值,然后如果必須將其包含在一個數組中,則更容易將其轉換為數組。 我自己我會把它保存在字典中,這樣你就可以像data[1]
那樣引用月份的值並獲得你需要的值而不必擔心索引。
rm = []
Month Station1 Station2 Station3
more = [[1, -999, 3, 2],
[1, 1, 0, -999],
[2, 4, -999, -999],
[3, -999, -999, 5]]
data = {}
for i in range(0, len(more)):
if more[i][0] not in data.keys():
data[more[i][0]] = []
for j in range(1, len(more[0])):
if (more[i][j] > -999):
data[more[i][0]].append(more[i][j])
rm = [v for k, v in data.items()]
print(rm)
這給出了這個 output:
[3, 2, 1, 0], [4], [5]]
有很多方法可以解決這個問題,您可能可以使用dict
或其他數據結構來解決這個問題。 這是一個使用字典來保存列表的解決方案。 此解決方案效果很好,因為您希望將列表中的項目與月份編號相關聯,但同一月份可以跨越多個子列表。
在 python 中,您可以在不使用索引的情況下直接迭代列表,如果您需要索引,您可以只使用for index, item in enumerate(list)
而不是使用range
和len
。
嘗試:
from collections import defaultdict
d = defaultdict(list)
for row in more:
for val in row[1:]:
if val != -999:
# row[0] stores the month value which we want to key on
d[row[0]].append(j)
rm = list(d.values())
這仍然會在rm
中產生與以前相同的列表集,但是您會丟失哪些值屬於哪個月份之間的關聯。 最好將它們保存為字典格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.