简体   繁体   English

Python嵌套元组列表

[英]Python Nested tuples to list

I have a mysql query that runs and selects all of the Id's that match the select statement: 我有一个mysql查询,该查询运行并选择与select语句匹配的所有ID:

first_seen_select = "SELECT Id FROM domains_archive WHERE current_epoch = " + current_epoch + " AND first_seen IS NULL"
cur.execute(first_seen_select)

The output of cur.fetchall() is cur.fetchall()的输出是

((1,), (2,), (3,), (4,), (5,), (6,), (7,))

How do i extract these nested tuple Id #'s and convert them into a single list that i can iterate over? 我如何提取这些嵌套的元组ID#并将其转换为可以迭代的单个列表?

If i run the following i get: 如果我运行以下命令,则会得到:

>>> bleh = cur.fetchall()
>>> for i in bleh:
...   print(i)
... 
(1,)
(2,)
(3,)
(4,)
(5,)
(6,)
(7,)

you can use a simple list comprehension: 您可以使用简单的列表理解:

[y for x in l for y in x]

Or with more meaningful variable names: 或者使用更有意义的变量名称:

[item for sublist in l for item in sublist]

this will result in: 这将导致:

In [8]: l = ((1,), (2,), (3,), (4,), (5,), (6,), (7,))

In [9]: [y for x in l for y in x]
Out[9]: [1, 2, 3, 4, 5, 6, 7]

You could use: 您可以使用:

result = [x[0] for x in cur.fetchall()]
print(result)

Output 输出量

[1, 2, 3, 4, 5, 6, 7]
lt = ((1,), (2,), (3,), (4,), (5,), (6,), (7,))

from itertools import chain

>>> list(chain.from_iterable(lt))

[1, 2, 3, 4, 5, 6, 7]

There's a fun (although not clear/unpractical) way to flatten it using sum() : 有一种有趣的方式(尽管不明确/不切实际)使用sum()来展平它:

In [1]: bleh = ((1,), (2,), (3,), (4,), (5,), (6,), (7,))

In [2]: sum(bleh, ())
Out[2]: (1, 2, 3, 4, 5, 6, 7)

It works like that - iterates over the outer tuple and sums all the values inside: 它像这样工作-遍历外部元组并求和所有内部值:

In [3]: (1,) + (2,) + (3,) + (4,) + (5,) + (6,) + (7,)
Out[3]: (1, 2, 3, 4, 5, 6, 7)

And, as you see, if you add a tuple to a tuple, you get another tuple with all the values of those tuples. 而且,如您所见,如果将一个元组添加到一个元组,则将获得具有这些元组的所有值的另一个元组。

By passing an empty tuple - () - as a second argument to the sum() function, we basically tell it to use it as an initial argument to start adding from, so it would actually work like that: 通过将空的元组()作为第二个参数传递给sum()函数,我们基本上告诉它使用它作为初始参数来开始添加,因此它实际上将像这样工作:

In [4]: () + (1,) + (2,) + (3,) + (4,) + (5,) + (6,) + (7,)
Out[4]: (1, 2, 3, 4, 5, 6, 7)

A general way to create a list from a nested tuple would be: 从嵌套元组创建列表的一般方法是:

def tupleToList(nestedTuple):
    def gen(tuple_):
        for item in tuple_:
            if type(item) is tuple:
                yield from gen(item)
            else:
                yield item
    return [value for value in gen(nestedTuple)]

Note that everything is flattened. 请注意,一切都变平了。 Example usage: 用法示例:

>>> print(tupleToList((('a','b'), ('c', 'd', ('e')))))
['a', 'b', 'c', 'd', 'e']

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

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