如何同时运行2个列表循环,以便循环中的每个项目匹配? [蟒蛇]

时间:2014-11-21 16:48:02

标签: python multithreading asynchronous matplotlib

我正在编写一个使用matplotlib绘制数据的代码。数据来自数千个文本文件。我能够编写可以绘制数据的循环。现在,我想用一个来自另一个文件的信息为每个图添加一个标签,我将其列入一个列表:

import os
import matplotlib.pylab as plt
import numpy as np
from datetime import datetime, timedelta


time = []
t1 = []
t2 = []
t3 = []
t4 = []
t5 = []
t6 = []
newdate = []

temps = open('/Users/datafile_with_temperatures.txt','r')
sepfile = temps.read().replace('\n','').split('\r')
temps.close()

for plotpair in sepfile:
    data = plotpair.split('\t')
    time.append(float(data[0]))
    t1.append(float(data[1]))
    t2.append(float(data[2]))
    t3.append(float(data[3]))
    t4.append(float(data[4]))
    t5.append(float(data[5]))
    t6.append(float(data[6]))

for datapoint in t2,t3,t4,t5,t6:
    temperatures = np.array([t2,t3,t4,t5,t6]).mean(0).tolist()


os.chdir('/Users/datafile')
path = os.listdir('/Users/datafiles')
for file in path and temperature_point in temperatures:
    MtoC = []
    Pressure = []
    readfile = open(file,'r')

    datalines = readfile.read().split("\n")
    useful_data = []

    for line in datalines:
        line = ''.join([x for x in line if x not in [",", "\r"]])
        data = [float(item) for item in line.split()]
        useful_data.append(data)
    combined_data = [MtoC.extend(sub_list) for sub_list in useful_data]
    Mass_to_charge = MtoC[::2]
    Pressure = MtoC[1::2]

    plt.plot(Mass_to_charge,Pressure)
    plt.title(file)
    plt.text(60, 1e-07, temperature_point)
    plt.xlabel('Mass to Charge Ratio')
    plt.ylabel('Pressure (torr)')
    plt.yscale('log')
    plt.ylim([1e-10,1e-05])
    plt.savefig(file+'.jpg')
    plt.close()

我希望列表中的温度点列在图上。存在与绘图文本文件相同数量的温度点。有数千个文本文件包含用于制作图表的数据。每个文件相隔几秒钟,因为时间不是图中的变量。有一个文本文件有数千次对应于每个数据文件,具有该特定时间的温度。我想运行循环,因此它将绘制第一个数据文件并将第一个温度点添加为绘图上的文本并循环遍历每个文件并执行相同的操作。

2 个答案:

答案 0 :(得分:2)

  

块引用

结帐itertools.izip()

from itertools import izip

for d2,d3,d4,d5,d6 in izip(t2,t3,t4,t5,t6):
    ...

izip()zip()类似,但生成迭代器,而zip()一次解析它的输入并将一个巨大的对象传递给循环,这可能导致更大的数据集出现问题,而且速度较慢。

根据@ cyber的评论进行编辑:这只适用于Python 2.x.在Python 3.x中,内置zip()完成了izip()在这里所做的事情。

答案 1 :(得分:1)

可以使用zip解决此类行为,然后根据需要解压缩元素。请参阅以下简单示例:

l1 = [1,3,5,7,9]
l2 = [2,4,6,8,0]

for i1, i2 in zip(l1, l2):
    print('First: {}, Second: {}'.format(i1, i2))

输出

First: 1, Second: 2
First: 3, Second: 4
First: 5, Second: 6
First: 7, Second: 8
First: 9, Second: 0