从Python列表中删除值
我有一个由空格分隔的单行名称和值的大文件:
name1 name2 name3....
长长的名称列表后面是与名称对应的值列表。值可以是 0-4 或 na。我想要做的是合并数据文件,并在值为 na
时删除所有名称和值。
例如,此文件中名称的最后一行如下所示:
namenexttolast nameonemore namethelast 0 na 2
我想要以下输出:
namenexttolast namethelast 0 2
我该怎么做这是使用Python吗?
I have a large file of names and values on a single line separated by a space:
name1 name2 name3....
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
I would like the following output:
namenexttolast namethelast 0 2
How would I do this using Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设您将名称读入一个列表,然后将值读入另一个列表。一旦有了
names
和values
列表,您就可以执行以下操作:result
现在是值不是“na”的所有名称的列表”。Let's say you read the names into one list, then the values into another. Once you have a
names
andvalues
list, you can do something like:result
is now a list of all names whose value is not "na".更新
根据 Paul 的建议进行了小幅改进。我确信列表理解相当不Pythonic,因为它利用了
list.append
返回None
的事实,因此两个append
表达式都将是评估后,将构建一个None
值列表并立即丢弃。Update
Minor improvement after suggestion from Paul. I'm sure the list comprehension is fairly unpythonic, as it leverages the fact that
list.append
returnsNone
, so bothappend
expressions will be evaluated and a list ofNone
values will be constructed and immediately thrown away.我同意 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.
或者说您有一个从文件中读取的字符串。我们将此字符串称为“s”
应该为您提供除“na”编辑之外的所有字符串
:上面的代码显然没有执行您想要的操作。
下面的应该可以工作
or say you have a string which you have read from a file. Let's call this string as "s"
should give you all the strings except for "na"
edit: the code above obviously doesn't do what you want it to do.
the one below should work though
如果您想对值进行分组,您可以创建一个元组列表(注释掉行)
If you'd rather group the vals, you could create a list of tuples instead (commented out line)
这是一个仅使用迭代器加上单个缓冲区元素的解决方案,没有调用 len 也没有创建其他中间列表。 (在Python 3中,只需使用
map
和zip
,无需从itertools导入imap
和izip
。)印刷:
Here is a solution that uses just iterators plus a single buffer element, with no calls to len and no other intermediate lists created. (In Python 3, just use
map
andzip
, no need to importimap
andizip
from itertools.)Prints: