使用Python列表和数组

时间:2018-07-27 12:44:26

标签: python arrays

在使用多维数组多年之后,“ 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中使用该文件,提取并处理任何随机元素。
我意识到必须将文件转换为列表,然后使用列表。
文件的长度(数字记录)是动态的,宽度(每个记录中的元素)是固定的。 哪一种最有效的Python方式? 如果需要,我可以更改文件格式(分隔符等)。
新修改:
根据我收到的一些答复中的一些线索,我设法取得了进展,但问题仍然存在。
这是我所做的,但是最后,不能使它像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],'

3 个答案:

答案 0 :(得分:2)

如果您确实可以随意设置文件格式,则只需将其设置为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])

答案 1 :(得分:0)

尝试一下:

with open("filename.txt","r") as f:
    [[hex(r) for r in e.split(",")] for e in f.read().replace("\n","")[1:-2].split("],[")]

答案 2 :(得分:0)

好吧,经过大量的测试和尝试,我发现了如下的(简单)解决方案:

我有以下格式的excel csv输出文件:(逗号和方括号已在Excel中添加):

File.ReadAllBytes

我操纵了数据并“清理”了它,使其成为Python 2-dim List格式 (必须删除换行符,删除结尾的逗号,添加开始和结束括号,请参阅我原来的问题编辑)):

    [0x0,0x42,0x2A], [0x229,0x44,0x7C], [0x452,0x40,0x03], [0xCF9,0x4E,0x08],

问题是,尽管它看起来像2维列表,但它被Python解释为字符串

最终,在旧线程1的帮助下,我找到了有关如何将“合法” Python字符串转换为Python列表的解决方案: myList = eval(字符串)

之后,该结构的行为就像一个漂亮的2维列表(数组)。 很简单,但是花了我几个小时才找到。

完整代码:

[[0x0,0x42,0x2A],[0x229,0x44,0x7C],[0x452,0x40,0x03],[0xCF9,0x4E,0x08]]

感谢所有尝试提供帮助的人。