我想将元组中的值移动到列表中

2024-09-30 16:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

rows = [(747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57')]
alr_exist2 = []
ex = 0
for row in rows :
            ex = row
            alr_exist2.append(ex[0])
            ex = 0
print(alr_exist2)

如果我运行上述代码,我需要以下输出:

[747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57']

我如何修复错误


Tags: 代码infor错误nullexrowsrow
3条回答

I think, you have to unpack the list of tuples, first. Then insert the data into a freshed list.

rows = [(747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57')]

newList = []

for row in rows[0]: 
    """Here I specified the first tuple in the List because 
       there's only one tuple in the list. If there're more than 
       one, you have to make `nasted loop` >> 2d looping."""

    newList.append(row)

Print(newList)

输出

[747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57']

^{}也是一个很好的pythonic解决方案

rows = [(747652126187978752, 'NULL', 'NULL'), ('NULL', '2020-11-03 18:46:57')]
res = list(itertools.chain(*rows))

输出

>>> rows = [(747652126187978752, 'NULL', 'NULL'), ('NULL', '2020-11-03 18:46:57')]
>>> list(itertools.chain(*rows))
[747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57']
>>> rows = [(747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57')]
>>> list(itertools.chain(*rows))
[747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57']

您只需将其展平:

alr_exist2 = [item for sublist in rows for item in sublist]

输出:

[747652126187978752, 'NULL', 'NULL', 'NULL', '2020-11-03 18:46:57']

相关问题 更多 >