简体   繁体   English

在python中不可迭代的列表或元组

[英]a list or tuple that is not iterable in python

i am looking for a data collection which is NOT iterable. 我正在寻找一个不可迭代的数据收集。

reason behind it is, there is some code which merges multiple results by adding them to a new list and then calling the "list.extend" function. 其背后的原因是,有一些代码通过将多个结果合并到新列表中,然后调用“ list.extend”函数来合并这些结果。

i tried tuple, but it is iterable, im looking for a built in collection which is not iterable. 我尝试了元组,但它是可迭代的,即时通讯正在寻找一个不可迭代的内置集合。

what it does: 它能做什么:

>>> t1 = tuple([1,2,3])
... t2 = tuple([4,5,6])
... l = list()
... 
>>> l.extend(t1)
>>> l.extend(t2)
>>> 
>>> l
[1, 2, 3, 4, 5, 6]

what i want l to be is: 我要我成为的是:

[(1,2,3), (4,5,6)]

please bare in mind i can only change the t1, t2 variables.... it has to go through extent. 请记住,我只能更改t1,t2变量...。它必须经过范围。

Your problem is not that the tuple is iterable. 您的问题不是元组是可迭代的。 Making the tuple non-iterable won't help because extending a list with a non-iterable simply doesn't work. 使元组成为不可迭代的元素无济于事,因为用不可迭代的元素扩展列表根本行不通。

>>> l = []
>>> l.extend(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

What you need to do, is wrap your tuples in a list: 您需要做的是将元组包装在一个列表中:

>>> t1 = (1,2,3)
>>> t2 = (4,5,6)
>>> l.extend([t1])
>>> l.extend([t2])
>>> l
[(1, 2, 3), (4, 5, 6)]
>>> 

You can also extend the list with both tuples at the same time: 您还可以同时使用两个元组扩展列表:

>>> l.extend([t1,t2])
>>> l
[(1, 2, 3), (4, 5, 6), (1, 2, 3), (4, 5, 6)]
>>> 

You can use append feature of a list eg:- 您可以使用列表的附加功能,例如:-

>>> t1 = tuple([1,2,3])
>>> t2 = tuple([4,5,6])
>>> l = list()
>>> l.append(t1)
>>> l.append(t2)
>>> l # [(1,2,3), (4,5,6)]

you could create a child class of list with extend and __iadd__ methods overridden, so if a tuple is passed as a parameter, it appends instead of extending: 您可以创建具有extend__iadd__方法被覆盖的list的子类,因此,如果将元组作为参数传递,它将追加而不是扩展:

class MyList(list):
    def __fake_extend(self,other):
        if isinstance(other,tuple):
            self.append(other)
        else:
            list.extend(self,other)

    def __iadd__(self,other):
        self.__fake_extend(other)
        return self
    def extend(self,other):
        self.__fake_extend(other)

t1 = (1,2,3)
t2 = (4,5,6)

l = MyList()

l.extend(t1)
l.extend(t2)
l.extend([4,2,4,5])
print(l)

result: 结果:

[(1, 2, 3), (4, 5, 6), 4, 2, 4, 5]

the tuples have been appended, the items of the list as well (since they were contained in a list not a tuple ) 元组已附加,列表中的项目也已附加(因为它们包含在列表中而不是tuple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM