【发布时间】:2018-08-20 21:45:21
【问题描述】:
我需要在for in 循环期间修改一个元组,以便迭代器在该元组上进行迭代。
据我了解,元组是不可变的;所以tup = tup + (to_add,) 只是重新分配tup,而不是更改原始元组。所以这很棘手。
这是一个测试脚本:
tup = ({'abc': 'a'}, {'2': '2'})
blah = True
to_add = {'goof': 'abcde'}
for i in tup:
if blah:
tup = tup + (to_add,)
blah = False
print(i)
哪些打印:
{'abc': 'a'}
{'2': '2'}
我想要的是打印出来:
{'abc': 'a'}
{'2': '2'}
{'goof': 'abcde'}
据我了解,我需要“重新指向”隐式元组迭代器中间脚本,以便它指向新的元组。 (我知道这是一件非常糟糕的事情)。
此脚本访问有问题的 tuple_generator:
import gc
tup = ({'abc': 'a'}, {'2': '2'})
blah = True
to_add = {'goof': 'abcde'}
for i in tup:
if blah:
tup = tup + (to_add,)
blah = False
refs = gc.get_referrers(i)
for ref in refs:
if type(ref) == tuple and ref != tup:
refs_to_tup = gc.get_referrers(ref)
for j in refs_to_tup:
if str(type(j)) == "<class 'tuple_iterator'>":
tuple_iterator = j
print(i)
如何修改这个 tuple_generator 使它指向新的 tup,而不是旧的?这甚至可能吗?
我知道这是一个非常奇怪的情况,我无法更改 tup 是一个元组或者我需要使用隐式 for in,因为我正在尝试插入我无法更改的代码。
【问题讨论】:
-
您无法更改
tuple_iterator中的元组,就像您无法更改原始元组一样。因为它们是同一个元组。正如我在the answer that you copied this code from 中就您之前的问题已经解释过的那样。 -
为什么不在while循环中基于元组的长度来循环呢?类似
while i < len(tuple): i += 1 -
我知道我无法更改元组。我不是想改变元组。我试图将 tuple_iterator 指向新的元组。 “我如何修改这个 tuple_generator 使它指向新的 tup,而不是旧的?这甚至可能吗?”
-
不,这是不可能的。
tuple_iterator上没有 API 来更改它所指的元组,甚至没有一个私有和未记录的元组。 -
编写你自己的协程并
send新的元组添加到它。