相关疑难解决方法(0)

将Python int转换为big-endian字节串

我有一个非负的int,我想有效地将​​它转换为包含相同数据的big-endian字符串.例如,int 1245427(0x1300F3)应该生成一个长度为3的字符串,其中包含三个字符,其字节值为0x13,0x00和0xf3.

我的整数是35(基数为10)的数字.

我该怎么做呢?

python

56
推荐指数
6
解决办法
10万
查看次数

Python 3字节格式化

在Python 3中,可以格式化一个字符串,如:

"{0}, {1}, {2}".format(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

但是如何格式化字节?

b"{0}, {1}, {2}".format(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

加油AttributeError: 'bytes' object has no attribute 'format'.

如果没有format字节方法,如何格式化或"重写"字节?

python string-formatting python-3.x

44
推荐指数
5
解决办法
4万
查看次数

如何在Python 3.2或更高版本中使用'hex'编码?

在Python 2中,要获得字符串中十六进制数字的字符串表示,您可以这样做

>>> '\x12\x34\x56\x78'.encode('hex')
'12345678'
Run Code Online (Sandbox Code Playgroud)

在Python 3中,它不再起作用(在Python 3.2和3.3上测试):

>>> '\x12\x34\x56\x78'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: unknown encoding: hex
Run Code Online (Sandbox Code Playgroud)

这里至少有一个答案提到hex在Python 3中已经删除了编解码器.但是,根据文档,它在Python 3.2中被重新引入,作为"字节到字节映射".

但是,我不知道如何使这些"字节到字节映射"工作:

>>> b'\x12'.encode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)

而且文档也没有提到(至少不是我看的地方).我一定错过了一些简单的东西,但我看不出它是什么.

python encoding hex python-3.x

29
推荐指数
5
解决办法
3万
查看次数

Python 字节文字

我认为这是一个 python 新手问题,但是如何将单个字节(在本例中为零)写入文件?

我有这个代码:

f = open("data.dat", "wb")
f.write(0)
f.close()
Run Code Online (Sandbox Code Playgroud)

但在写入行上出现错误:

类型错误:需要类似字节的对象,而不是“int”

我想我需要用字节文字替换 0,但无法弄清楚语法。我所有的搜索都告诉我有关将字符串转换为字节的信息。我尝试过0B,但没有成功。

python python-3.x

8
推荐指数
1
解决办法
2929
查看次数

从程序中使用Python的`timeit`,但其功能与命令行相同?

例如,文档说:

但请注意,只有在使用命令行界面时,timeit才会自动确定重复次数.

有没有办法从Python脚本中调用它并自动确定重复次数,只返回最短的数字?

python timeit

6
推荐指数
1
解决办法
1087
查看次数

哈希 np.array -&gt; int 的确定性方法

我正在创建一个将大型 numpy 数组存储在pyarrow.plasma. 我想给每个数组一个唯一的、确定性的 plasma.ObjectIDnp.array遗憾的是不可散列我当前的(损坏的)方法是:

import numpy as np
from pyarrow import plasma
def int_to_bytes(x: int) -> bytes:
    return x.to_bytes(
        (x.bit_length() + 7) // 8, "big"
    )  # /sf/ask/1471238891/
def get_object_id(arr):
    arr_id = int(arr.sum() / (arr.shape[0]))
    oid: bytes = int_to_bytes(arr_id).zfill(20)  # fill from left with zeroes, must be of length 20
    return plasma.ObjectID(oid)
Run Code Online (Sandbox Code Playgroud)

但这很容易失败,例如:

arr = np.arange(12)
a1 = arr.reshape(3, 4)
a2 = arr.reshape(3,2,2)
assert get_object_id(a1) != get_object_id(a2), 'Hash collision'
# another good test case …
Run Code Online (Sandbox Code Playgroud)

python hash numpy pyarrow

3
推荐指数
1
解决办法
1607
查看次数

标签 统计

python ×6

python-3.x ×3

encoding ×1

hash ×1

hex ×1

numpy ×1

pyarrow ×1

string-formatting ×1

timeit ×1