首页 > 解决方案 > 使用 Python 列表和数组

问题描述

经过多年与多维数组的合作,“List”的 Python 数组概念对我来说似乎相当复杂(尽管据说它更出色)。
我有很长的(数千行)二维数组文件,其十六进制值具有以下格式(可以有或没有行分隔):

[0xF26,0x70,0x66],[0x1158,0x72,0xA6],[0x1388,0x72,0xB6],
[0x15BA,0x4E,0x08],[0x17E9,0x70,0x92],[0x1A1D,0x72,0x94],
[0x1C4F,0x72,0xB4],[0x4409,0x4A,0x14], etc. etc.

我希望在 Python 中使用该文件,提取和操作任何随机元素。
我意识到我必须将文件转换为列表,并使用该列表。
文件的长度(记录数)是动态的,宽度(每条记录中的元素)是固定的。哪种是最有效的 Pythonian 方式?如果需要,我可以更改文件格式(分隔字符等)。
新编辑:
根据我收到的少数回复中的一些线索,我设法取得了进展,但问题仍然存在。
这是我所做的,但最后,我不能让它像 2-dim 数组一样运行,如附件代码所示:

>>> test1 = open("C:/testdata1.txt", 'r') #This opens automatically as a 
#list, but with line breaks and no start and end brackets.
>>> test2 = test1.read()                # Convert to string
>>> test2 = test2.replace("\n","")      # Remove line breaks
>>> test2 = "[" + test2 + "]"           # Add brackets
>>> print(test2)

# The result looks like pure 2-dim list, but does not behave like one:
[[0x0,0x42,0x2A],[0x229,0x44,0x7C],[0x452,0x40,0x03],[0xCF9,0x4E,0x08], 
[0xF26,0x70,0x66],[0x1158,0x72,0xA6],[0x1388,0x72,0xB6],]

#This gives an error
>>> print(test2[1][2])
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    print(test2[1][2])
IndexError: string index out of range

#But it runs like one-dim array of chars
>>> print(test2[8])
4
>>>
# If I copy and paste the above list as a new list, it works nicely!

Can better use:
>>> with open("C:/testdata1.txt", 'r') as file:
     for line in file:
     file.read()
# But, again, reading result with line breaks, no brackets.
 '[0x229,0x44,0x7C],\n[0x452,0x40,0x03],\n[0xCF9,0x4E,0x08],
 \n[0xF26,0x70,0x66],\ n[0x1158,0x72,0xA6],\n[0x1388,0x72,0xB6],'

标签: pythonarrays

解决方案


如果您真的可以随意格式化文件,只需将其设为 Python 模块:

# bigarray.py

bigarray = [
[0xF26,0x70,0x66],[0x1158,0x72,0xA6],[0x1388,0x72,0xB6],
[0x15BA,0x4E,0x08],[0x17E9,0x70,0x92],[0x1A1D,0x72,0x94],
[0x1C4F,0x72,0xB4],[0x4409,0x4A,0x14], # etc. etc.
]

来自其他模块:

# mymodule.py

from bigarray import bigarray

print(bigarray[1][2])

推荐阅读