python - 使用 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],'
解决方案
如果您真的可以随意格式化文件,只需将其设为 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])
推荐阅读
- html - 在 html 画布内创建一个透明的文本框,该文本框呈现在画布的顶部
- javascript - 如何使用 useEffect 钩子和异步调用编写 React 组件单元测试?
- javascript - 如何从电台组中找到单个电台并设置检查属性?
- amazon-web-services - 如何为 AWS IAM 中的所有现有用户和新用户添加 IAM 策略?
- botframework - Azure 核心机器人 Luis 集成在通过模拟器运行时出错:操作返回无效状态代码“找不到资源”
- javascript - 有什么方法可以像绝对定位一样按像素定位 div 但它占用空间?
- java - 在任何值的情况下,带有一些 where 条件的准备好的语句
- svg - 嵌入式 SVG 的高度和宽度属性未反映在浏览器中
- ruby-on-rails - 链接不会“发布”正确的数据以采取行动。(仅获取最后一个 id)
- java - 带有单元测试的 Quarkus BeanManager