我在文本文件中有以下类型的数据。
15 1
23 0
39 -1
71 -1
79 1
95 1
127 -2
151 2
183 1
191 -1
239 0
247 3
我想从文本文件中创建一个2d列表,如下所示。我可以使用下面给出的代码执行以下结果
[[15, 1.36896146582243],
[23, 0.000000000000000],
[39, 0.848993860380692],
[71, 0.629227476540724],
[79, 0.596517662620081],
[95, 0.543970127117099],
[127, 1.88189324753006],
[151, 1.72587115688942],
[183, 0.391932527534896],
[191, 0.383636720228727]]
但是我不想要所有条目,我只想要在源文本文件的第二列中具有非零条目的条目。例如,我不想要条目
23 0
239 0
如何将条件语句添加到我的代码中。
with open("path.text") as file:
R = [[int(x) for x in line.split()] for line in file]
答案 0 :(得分:2)
没有必要把它变成单个列表理解表达式 - 在你的情况下它不会更快:
result = []
with open("path.text", "r") as f:
for line in f:
line = line.split()
if len(line) < 2: # just to make sure we have both columns
continue
column_2 = float(line[1]) # since, it appears, you have floats
if column_2:
result.append([int(line[0]), column_2]) # turn column 1 to int, too
更新 - 基准时间 - 如果您定义的功能彼此紧密匹配(因此没有浮动处理或验证如上):
def f1():
with open("path.text", "r") as f:
return [[int(x) for x in line.split()] for line in f if '0' not in line.split()]
def f2():
result = []
with open("path.text", "r") as f:
for line in f:
line = line.split()
if line[1] != '0':
result.append([int(line[0]), int(line[1])])
return result
path.text
包含与OP和assert f1() == f2()
次传递相同的数据,以下是我系统上的一些结果:
Python 3.5.1, 64-bit
f1() - 100,000 loops: 10.834s
f2() - 100,000 loops: 9.9601s
Python 2.7.11 64-bit
f1() - 100,000 loops: 6.9243s
f2() - 100,000 loops: 6.4012s
其中大部分实际上是I / O,相对而言,处理的差异实际上要大得多。
答案 1 :(得分:1)
pythonic解决方案是将if语句添加到列表解析
with open("path.text") as file: R = [[int(x) for x in line.split()] for line in file if line[1] != '0']