【问题标题】:How to create a pointer to a list, such that accessing via the pointer gives immutable elements?如何创建指向列表的指针,以便通过指针访问提供不可变元素?
【发布时间】:2021-02-04 10:27:50
【问题描述】:

假设

my_list = [[1], [2], [3], ["a"], [5]]

我想要

my_imm = ImmutableList(mylist)

这样

my_imm[2][0] = 0

要么抛出错误,要么不改变my_list[2]

有没有这样的构造不复制所有数据

还假设 my_list 很长,我不想要一个转换,而是一个惰性迭代器。


请注意,这不是 this 的副本,因为我希望 THE ELEMENTS 是不可变的。

元组不能立即解决这个问题。

【问题讨论】:

  • @AndrewPye 是的,但我的元素不一定是数字
  • numpy 接受字符串,但...确实要求如果您有列表列表,则所有列表都具有相同的尺寸。否则嵌套列表将是可变的
  • @AndrewPye numpy 不会复制施工中的所有内容吗?我将数据输入作为列表。

标签: python list tuples immutability


【解决方案1】:

使用生成器将元素作为元组获取:

my_imm = (tuple(e) for e in my_list)

【讨论】:

  • 越小越好(你比我早到了)+1
  • 但这还不创建副本吗?
  • 别客气。它使用对值的引用创建元组。
【解决方案2】:
from collections.abc import Iterable
from typing import Iterator


class MyImm(Iterable):
    def __init__(self, iterable: Iterable):
        self._iterator = iter(iterable)

    def __next__(self) -> Iterator:
        return tuple(next(self._iterator))

    def __iter__(self):
        return self


my_list = [[1], [2], [3], ["a"], [5]]
my_imm = MyImm(my_list)

for i, e in enumerate(my_imm):
    print(my_list)
    if i == 2:
        e[0] = 0

print(my_list)

输出:

"C:/code/EPMD/Kodex/Applications/EPMD-Software/LocationService/ablation/ssss.py",
line 22, in <module>
   e[0] = 0 TypeError: 'tuple' object does not support item assignment [[1], [2], [3], ['a'], [5]] [[1], [2], [3], ['a'], [5]]
[[1], [2], [3], ['a'], [5]]

【讨论】:

    猜你喜欢
    • 2023-02-16
    • 2018-06-02
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 2013-05-26
    • 2017-01-04
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多