简体   繁体   English

使用列表理解提取元组列表

[英]Extracting list of tuples using list comprehension

I am trying to extract data's from list of list of tuples but I am having an issue because they have different output from normal for loop and this list comprehension loop:我正在尝试从元组列表中提取数据,但我遇到了问题,因为它们与普通 for 循环和此列表理解循环的输出不同:

Here is my sample data and actually came from my database and return it as unicode and I just converted as a list:这是我的示例数据,实际上来自我的数据库并将其作为 unicode 返回,我只是将其转换为列表:

[[(1970, u'0238'), (1971, u'0243'), (2110, u'0929'), (2108, u'0930'), (1972, u'0932'), (1973, u'0934')]]
[[(1970, u'0238'), (1971, u'0243'), (2110, u'0929'), (2108, u'0930'), (1972, u'0932'), (1973, u'0934')]]
[[(2108, u'0930')], [(3012, u'1')]]
[[(2108, u'0930')], [(3012, u'1')]]
[[(2108, u'0930')], [(3012, u'1')]]
[[(2108, u'0930')], [(3012, u'1')]]

And by using my simple for loop which is the correct output:通过使用我的简单 for 循环,这是正确的输出:

for i in datas:
    print i
[(1970, u'0238'), (1971, u'0243'), (2110, u'0929'), (2108, u'0930'), (1972, u'0932'), (1973, u'0934')]
[(1970, u'0238'), (1971, u'0243'), (2110, u'0929'), (2108, u'0930'), (1972, u'0932'), (1973, u'0934')]
[(2108, u'0930')]
[(3012, u'1')]
[(2108, u'0930')]
[(3012, u'1')]
[(2108, u'0930')]
[(3012, u'1')]
[(2108, u'0930')]
[(3012, u'1')]

But if I will use the list comprehension style the out will be now different:但是如果我将使用列表理解样式,输出现在将不同:

print [i for i in datas]
[[(1970, u'0238'), (1971, u'0243'), (2110, u'0929'), (2108, u'0930'), (1972, u'0932'), (1973, u'0934')]]
[[(1970, u'0238'), (1971, u'0243'), (2110, u'0929'), (2108, u'0930'), (1972, u'0932'), (1973, u'0934')]]
[[(2108, u'0930')], [(3012, u'1')]]
[[(2108, u'0930')], [(3012, u'1')]]
[[(2108, u'0930')], [(3012, u'1')]]
[[(2108, u'0930')], [(3012, u'1')]]

Any advice or suggestions thanks in advance!任何意见或建议提前致谢!

by for loop, you are printing the items inside the list, but in list comprehension itself creating a outer list.通过 for 循环,您正在打印列表内的项目,但在列表理解本身中创建一个外部列表。

I think you need,我想你需要,

 print sum([i for i in datas],[])

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

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