列表理解以合并python中的各种列表 [英] list comprehension to merge various lists in python

查看:82
本文介绍了列表理解以合并python中的各种列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要绘制大量数据样本,每个样本都存储在整数列表中.我想从许多串联的列表中创建一个列表,以便使用enumerate(big_list)对其进行绘制,以获得固定偏移量的x坐标. 我当前的代码是:

I need to plot a lot of data samples, each stored in a list of integers. I want to create a list from a lot of concatenated lists, in order to plot it with enumerate(big_list) in order to get a fixed-offset x coordinate. My current code is:

biglist = []
for n in xrange(number_of_lists):
    biglist.extend(recordings[n][chosen_channel])
for x,y in enumerate(biglist):
    print x,y

注意:number_of_lists和selected_channel是在其他地方定义的整数参数,例如print x,y(实际上还有其他语句可以绘制这些点.

Notes: number_of_lists and chosen_channel are integer parameters defined elsewhere, and print x,y is for example (actually there are other statements to plot the points.

我的问题是: 有没有更好的方法,例如列表解析或其他操作,可以在没有循环和预先声明的空列表的情况下达到相同的结果(合并列表)?

My question is: is there a better way, for example, list comprehensions or other operation, to achieve the same result (merged list) without the loop and the pre-declared empty list?

谢谢

推荐答案

import itertools
for x,y in enumerate(itertools.chain(*(recordings[n][chosen_channel] for n in xrange(number_of_lists))):
    print x,y

您可以将itertools.chain()视为管理各个列表的迭代器.它会记住您在哪个列表中以及该列表中的位置.这样可以节省创建大型列表所需的所有内存.

You can think of itertools.chain() as managing an iterator over the individual lists. It remembers which list and where in the list you are. This saves you all memory you would need to create the big list.

这篇关于列表理解以合并python中的各种列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆