【发布时间】:2014-06-18 17:30:30
【问题描述】:
foo = open('words.txt').readlines()
[k.rstrip() for k in foo if k.rstrip() != '']
我想重复使用修改后的密钥,就像那样
[k.rstrip() for k in foo if k != '']
这可能吗?
# input (words.txt)
# this will be just some lines with one or more words separated by space.
# there will be no *special* case or anything
foo bar
baz
bar baz waz
# expected output
>>> ['foo bar', 'baz', 'bar baz waz']
【问题讨论】:
-
你能举个例子
foo是什么。 -
你真的不能那样做。列表推导式的目标表达式除了迭代项外无权访问任何内容。您必须要么基于
foo创建一个新的可迭代对象,要么写出一个显式循环而不是使用列表推导。 -
如果您可以发布一些更好的示例数据和预期的输出,那么我们可能会在可能的情况下提出更好的解决方案。
-
@awini-haudhary 实际上这是 正确 输入,但即使您的答案被接受,我也会添加预期输出;)
-
@Lucas 但是此数据中没有
\n,以防您的数据仅包含尾随或前导'\n',那么您可以放弃replace调用。
标签: python list python-2.7 list-comprehension