从python列表中删除值 [英] Removing values from a list in python
问题描述
我在一行中用空格分隔了一个包含名称和值的大文件:
I have a large file of names and values on a single line separated by a space:
name1 name2 name3....
在长长的名称列表之后是与名称对应的值列表.值可以是 0-4 或 na.我想要做的是合并数据文件并在值为 na
时删除所有名称和值.
Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the names and and values when the value is na
.
例如,这个文件中的最后一行名称是这样的:
For instance, the final line of name in this file is like so:
namenexttolast nameonemore namethelast 0 na 2
我想要以下输出:
namenexttolast namethelast 0 2
我将如何使用 Python 做到这一点?
How would I do this using Python?
推荐答案
我同意 Justin 的观点,而不是使用 zip 是个好主意.问题是如何将数据放入两个不同的列表中.这是一个应该可以正常工作的提案.
I agree with Justin than using zip is a good idea. The problems is how to put the data into two different lists. Here is a proposal that should work ok.
reader = open('input.txt')
writer = open('output.txt', 'w')
names, nums = [], []
row = reader.read().split(' ')
x = len(row)/2
for (a, b) in [(n, v) for n, v in zip(row[:x], row[x:]) if v!='na']:
names.append(a)
nums.append(b)
writer.write(' '.join(names))
writer.write(' ')
writer.write(' '.join(nums))
#writer.write(' '.join(names+nums)) is nicer but cause list to be concat
这篇关于从python列表中删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!