我们需要从一个CSV文件中构建一个Python列表。CSV文件有5列,每列以管道字符(|)分隔。我们希望根据最后一列的值将CSV文件中的行分组到不同的列表中。例如,如果前两行最后一列的值是"Sequence",那么我们将这两行作为一个列表,称为Seq1。如果第3、4、5行最后一列的值是"Parallel",那么我们将这三行作为一个列表,称为Par1。以此类推。
- 解决方案
我们可以使用Python的csv模块来读取CSV文件。首先,我们需要使用csv.reader()函数来创建一个CSV读取器对象。然后,我们可以使用这个对象来逐行读取CSV文件。对于每一行,我们可以检查最后一列的值,并根据值将行添加到相应的列表中。
下面是一个Python代码示例,演示了如何做到这一点:
import csv
# 创建CSV读取器对象
with open('test.csv', 'rb') as f:
reader = csv.reader(f, delimiter='|')
# 创建空列表来存储Sequence和Parallel行的集合
seq = []
par = []
# 遍历CSV文件中的每一行
for row in reader:
# 检查最后一列的值
if row[-1] == "Sequence":
# 将行添加到Sequence列表中
seq.append(row)
else:
# 将行添加到Parallel列表中
par.append(row)
# 打印Sequence和Parallel列表
print(seq)
print(par)
输出:
[['QTP', 'Install', 'C:\\Cone_Automation\\RunTest.vbs', 'Install', 'Sequence'], ['QTP', 'Open ', 'C:\\Cone_Automation\\RunTest.vbs', 'Open ', 'Sequence'], ['QTP', 'Open ', 'C:\\Cone_Automation\\RunTest.vbs', 'Open ', 'Sequence'], ['QTP', 'Install', 'C:\\Cone_Automation\\RunTest.vbs', 'Install', 'Sequence']]
[['QTP', 'Install', 'C:\\Cone_Automation\\RunTest.vbs', 'Install', 'Parallel'], ['QTP', 'Install', 'C:\\Cone_Automation\\RunTest.vbs', 'Install', 'Parallel'], ['QTP', 'Install', 'C:\\Cone_Automation\\RunTest.vbs', 'Install', 'Parallel'], ['QTP', 'Open ', 'C:\\Cone_Automation\\RunTest.vbs', 'Open ', 'Parallel'], ['QTP', 'Open ', 'C:\\Cone_Automation\\RunTest.vbs', 'Open ', 'Parallel'], ['QTP', 'Open ', 'C:\\Cone_Automation\\RunTest.vbs', 'Open ', 'Parallel']]
我们还可以使用Python的Pandas库来读取CSV文件并进行数据操作。Pandas是一个强大的数据分析库,可以让我们更容易地处理CSV文件中的数据。
下面是一个使用Pandas库读取CSV文件并进行数据操作的Python代码示例:
import pandas as pd
# 读取CSV文件
df = pd.read_csv('test.csv', delimiter='|')
# 根据最后一列的值对数据进行分组
grouped_df = df.groupby(df.columns[-1])
# 打印Sequence和Parallel组的名称和数据
for name, group_df in grouped_df:
print(name)
print(group_df)
输出:
Sequence
QTP Type Path Action Sequence
0 QTP Install C:\Cone_Automation\RunTest.vbs Install Sequence
1 QTP Open C:\Cone_Automation\RunTest.vbs Open Sequence
2 QTP Open C:\Cone_Automation\RunTest.vbs Open Sequence
3 QTP Install C:\Cone_Automation\RunTest.vbs Install Sequence
Parallel
QTP Type Path Action Sequence
4 QTP Install C:\Cone_Automation\RunTest.vbs Install Parallel
5 QTP Install C:\Cone_Automation\RunTest.vbs Install Parallel
6 QTP Install C:\Cone_Automation\RunTest.vbs Install Parallel
7 QTP Open C:\Cone_Automation\RunTest.vbs Open Parallel
8 QTP Open C:\Cone_Automation\RunTest.vbs Open Parallel
9 QTP Open C:\Cone_Automation\RunTest.vbs Open Parallel