【问题标题】:How to fix the code to work in HEX format?如何修复代码以十六进制格式工作?
【发布时间】:2021-08-11 09:44:02
【问题描述】:

帮助修复代码。我的脚本对列表中的偶数和奇数坐标进行排序,并且仅适用于十进制数格式的列表,但我需要修复代码以使用 HEX 格式(十六进制数格式)的列表

我对Python语言不太了解,但需要添加函数hex(str)

这是一个类似这样的列表List.txt

(0x52DF625,0x47A406E)
(0x3555F30,0x3323041)
(0x326A573,0x5A5E578)
(0x48F8EF7,0x98A4EF3)
(0x578FE62,0x331DF3E)
(0x3520CAD,0x1719BBB)
(0x506FC9F,0x40CF4A6)

Сode:

with open('List.txt') as fin,\
     open('Save+even.txt', 'a') as foutch,\
      open('Save-odd.txt', 'a') as foutnch:
    data = [line.strip() for line in fin]
    nch = [foutnch.write(str(i) + '\n') 
        for i in data if int(i[1:-1].split(',')[1]) % 2]
    ch = [foutch.write(str(i) + '\n') 
        for i in data if int(i[1:-1].split(',')[1]) % 2 != 1]

【问题讨论】:

  • 你在这里问了几个问题,但你从来没有accepted 一个答案。请阅读how to accept an answer,
  • 您可能需要查看contextlib.ExitStack() 以帮助清理with。
  • @JonSG 我不知道ExitStack。谢谢你提出来!我希望下次我做类似的事情时记得它......

标签: python python-3.x list hex


【解决方案1】:

这可能对您有用(我使用 StringIO 而不是真实文件 - 但添加了关于如何将其用于真实文件的评论)

in_file = StringIO("""(0x52DF625,0x47A406E)
(0x3555F30,0x3323041)
(0x326A573,0x5A5E578)
(0x48F8EF7,0x98A4EF3)
(0x578FE62,0x331DF3E)
(0x3520CAD,0x1719BBB)
(0x506FC9F,0x40CF4A6)
""")

even_file = StringIO()
odd_file = StringIO()

# with open( "List.txt") as in_file, open("Save-even.txt", "w") as even_file, open("Save-odd.txt", "w") as odd_file:
for line in in_file:
    x_str, y_str = line.strip()[1:-1].split(",")
    x, y = int(x_str, 0), int(y_str, 0)
    if y & 1:  # y is odd
        odd_file.write(line)
    else:
        even_file.write(line)

print("odd")
print(odd_file.getvalue())

print("even")
print(even_file.getvalue())

它输出:

odd
(0x3555F30,0x3323041)
(0x48F8EF7,0x98A4EF3)
(0x3520CAD,0x1719BBB)

even
(0x52DF625,0x47A406E)
(0x326A573,0x5A5E578)
(0x578FE62,0x331DF3E)
(0x506FC9F,0x40CF4A6)

诀窍是在将十六进制字符串转换为 int 时使用 base 0:int(x_str, 0),。见this answer。

【讨论】:

  • 如何放置 List.txt 文件的列表,因为它重 1GB。我想将整个结果保存在两个文件中:'Save + even.txt' / 'Save-odd.txt'
  • 如 cmets 中所述:在此 with 语句中使用 for 循环:with open( "List.txt") as in_file, open("Save-even.txt") as even_file, open("Save-odd.txt") as odd_file: 并删除所有 StringIO 内容。这只是为了让我的示例在这里独立。
  • 哦,输入文件的大小不是问题(嗯,1GB 在任何最近的硬件上都不应该是问题);我从来没有完全读过文件——我只是遍历它的行。
  • 我做了和你描述的一样的事,但是我得到了一个错误: Traceback (most recent call last): File "D:/script.py", line 8, in even_file.write (行)io.UnsupportedOperation:不可写
  • 如何正确描述代码?我正在使用python3。像这样pastebin.com/uuCn69HB
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2014-09-13
  • 2014-07-13
  • 2021-05-27
  • 2019-09-26
  • 1970-01-01
  • 2022-07-08
相关资源
最近更新 更多