python - 格式化序列中的整数(列表、元组、集合)

标签 python python-3.x python-3.6 python-3.7

我有一个类,其中一个成员是一个整数序列。它可能是listtupleset 之一。在打印 (__str__) 此类的实例时,我需要格式化整数但保留序列的类型。

举个例子,我有一个类

class A:
    def __init__(self, seq):
        self.seq = seq

和三个实例

a = A(seq=tuple(range(5, 12)))
b = A(seq=list(range(17, 21)))
c = A(seq=set(range(26, 31)))

我想为

提供以下输出
print(a)  # A(seq=(0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b))
print(b)  # A(seq=[0x11, 0x12, 0x13, 0x14])
print(c)  # A(seq={0x1a, 0x1b, 0x1c, 0x1d, 0x1e})

我的第一次尝试是这个(但它不起作用!这些项目表示为字符串。)

class A:

    def __str__(self):
        seq2 = self.seq.__class__(f"0x{i:02x}" for i in self.seq)
        return f"A(seq={seq2})"

# A(seq=('0x05', '0x06', '0x07', '0x08', '0x09', '0x0a', '0x0b'))
# A(seq=['0x11', '0x12', '0x13', '0x14'])
# A(seq={'0x1b', '0x1c', '0x1d', '0x1a', '0x1e'})

一种有效但看起来很笨拙的方法是:

class A:

    def __str__(self):
        item_str = ", ".join(f"0x{i:02x}" for i in self.seq)
        if isinstance(self.seq, list):
            o, c = "[", "]"
        elif isinstance(self.seq, tuple):
            o, c = "(", ")"
        elif isinstance(self.seq, set):
            o, c = "{", "}"
        else:
            raise ValueError
        return f"A(seq={o}{item_str}{c})"

# A(seq=(0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b))
# A(seq=[0x11, 0x12, 0x13, 0x14])
# A(seq={0x1a, 0x1b, 0x1c, 0x1d, 0x1e})

难道没有更优雅的版本吗?或者我是否必须将 listtupleset 子类化为允许在 __str__ 中设置格式选项的版本?

最佳答案

我会使用寻址字典:

class A:
    def __str__(self):
        wrappers = {
            list : "[]",
            tuple: "()",
            set  : "{}",
        }
        item_str = ", ".join(f"0x{i:02x}" for i in self.seq)
        o, c = wrappers.get(type(self.seq), "||")
        return f"A(seq={o}{item_str}{c})"

关于python - 格式化序列中的整数(列表、元组、集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56768657/

相关文章:

node.js - 如何修复 ‘Error: Can' 找不到 Python 可执行文件 "python",您可以设置 PYTHON 环境变量。” ubuntu Node js npm

python - 使用生成器在 Python 中通过 MQTT 将音频从麦克风流式传输到 Google Streaming 时出现问题

python - 使用嵌套列表迭代字典并在板位置打印

python - 在 Python 中对句子进行分词并重新连接结果

python - Python中的无限滚动背景

python-3.x - 当我在 Docker 中运行代码时,我收到一个 Django 错误 [Errno 2]。在本地运行时,一切正常。为什么?

Python正则表达式: replace a letter if it is not a part of the word in a list

tensorflow - 带有图像和标量的 keras 生成器

python - 列出列值在数据框中不唯一的行

python - 如何使用 python 使用 hmac-sha1 生成 oauth 签名?