【问题标题】:Reuse modified key in list comprehension在列表理解中重用修改后的键
【发布时间】: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


【解决方案1】:

这样做:

[x for x in (k.replace('\n', '').strip() for k in foo) if x]

看起来你想过滤掉空行,你可以这样做:

#Assuming `c` is the file object
>>> [line.rstrip() for line in c if not line.isspace()]
['foo bar', 'baz', 'bar baz waz']
#Demo
>>> foo = ['foo bar\n', 'baz\n', 'bar baz waz\n', '   \n']
>>> [line.strip() for line in foo if not line.isspace()]
['foo bar', 'baz', 'bar baz waz']

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2020-09-05
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多