使用三个括号从 python 中的数组中获取值
Using three brackets to get value from the array in python
从 pcap
文件中提取了 ts
和 buf
。并将值附加到 scr_ports
数组中。
我不确定下面使用的 [i][0][1]
语法。请解释一下好吗?
for ts, buf in pcap:
src_ports = []
src_ports[index].append([ts, buf])
buf = src_ports[i][0][1]
[n]
是索引运算符;它为您提供列表中的第 n 项。在 python 中,您没有多维数组,取而代之的是列表的列表。当你有:
arr = [[0, 1], [2, 3]]
print(arr[0]) # this prints [0, 1], that is 0th list in arr
print(arr[0][0]) # this prints 0, 0th item of 0th item an arr;
# 0th item in arr is [0, 1]; 0th item of that is 0
您可以将其扩展到更多维度的数组。
src_ports
将是一个 3D 数组:[ [[ts1, buf1], [ts2, buf2], ....], [...], ...]
.
所以,第一个 [i]
会给你 src_ports
中的第一个二维数组, [0]
会给你里面的第一个数组, [1]
会在一维数组中给你 buf
。
另外,你在循环中清除数组似乎很奇怪。这基本上意味着你 append
每次都清除数组,这对我来说毫无意义。
从 pcap
文件中提取了 ts
和 buf
。并将值附加到 scr_ports
数组中。
我不确定下面使用的 [i][0][1]
语法。请解释一下好吗?
for ts, buf in pcap:
src_ports = []
src_ports[index].append([ts, buf])
buf = src_ports[i][0][1]
[n]
是索引运算符;它为您提供列表中的第 n 项。在 python 中,您没有多维数组,取而代之的是列表的列表。当你有:
arr = [[0, 1], [2, 3]]
print(arr[0]) # this prints [0, 1], that is 0th list in arr
print(arr[0][0]) # this prints 0, 0th item of 0th item an arr;
# 0th item in arr is [0, 1]; 0th item of that is 0
您可以将其扩展到更多维度的数组。
src_ports
将是一个 3D 数组:[ [[ts1, buf1], [ts2, buf2], ....], [...], ...]
.
所以,第一个 [i]
会给你 src_ports
中的第一个二维数组, [0]
会给你里面的第一个数组, [1]
会在一维数组中给你 buf
。
另外,你在循环中清除数组似乎很奇怪。这基本上意味着你 append
每次都清除数组,这对我来说毫无意义。