python - 使用 `with` 语句命名列表元素

标签 python list sequence with-statement

我想用不同的名称 (fetch) 引用列表 (mem) 的元素 (mem[0]) :

mem = [0]
f = open("File.lx", "rb").read()
for b in f: mem += [b]
size = len(mem)

while mem[0] < size:        #using mem[0]
    char = (mem[0]*2)+1
    source = mem[char]
    target = mem[char + 1]

    mem[0] += 1
    mem[target] = mem[source]

我尝试使用 with 语句:

mem = [0]
f = open("File.lx", "rb").read()
for b in f: mem += [b]
size = len(mem)

with mem[0] as fetch:        #with statement
   while fetch < size:       #using mem[0] as fetch
    char = (fetch*2)+1
    source = mem[char]
    target = mem[char + 1]

    fetch += 1
    mem[target] = mem[source]

但是我得到了一个错误:

Traceback (most recent call last):
  File "C:\documents\test.py", line 6, in <module>
    with mem[0] as fetch:
AttributeError: __enter__

我认为这就是方法,因为这就是文件对象的处理方式:

with open("File.lx", "rb") as file:
    fileBytes = file.read()

我读了docs对于 with 语句,它表示已加载 __exit()____enter()__ 方法。根据我阅读后的理解和 AttributeError 中的内容,我的猜测是序列元素 (mem[0]) 没有 __enter()__ 方法。

最佳答案

正如评论中已经提到的,mem[0]是一个字面整数,没有 __enter____exit__ as 需要这些关键字起作用,如果您只使用 mem[0] 确实会更简单

但这太简单了,你可以做什么(作为练习实际上并不这样做) 是扩展 int类并添加__enter____exit__像这样:

class FancyInt(int):
    def __enter__(self):
        return self
    def __exit__(self, *args):
        pass

mem = [FancyInt(0)]
with mem[0] as fetch:
    print(fetch)

这很简洁,但是 fetchLITERAL! 的别名,如果您更改 fetch , mem[0]不会改变!

关于python - 使用 `with` 语句命名列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783074/

相关文章:

python - 如何在Python中通过中断创建事件系统

python - 用于搜索和导出到 csv 文件/Excel 表的 Shell 脚本

python - 在 tensorflow 中,我如何从生成器读取我的预测?

list - 如何将列表列表作为参数提供给机器人框架测试模板

Javascript 如何创建一个按顺序包含数字的对象

python - 修复我的函数的返回格式

python - django 将 models.DecimalField 与表单结合起来 -> 错误 : quantize result has too many digits for current context

c++ - std::list::sort 和指向元素的指针

list - 追加到 Elm 列表中

java - 是否可以在没有列的情况下在 JPA/Hibernate 中创建和使用序列生成器?