【问题标题】:print loop of results into variable将结果循环打印到变量中
【发布时间】:2017-01-27 13:51:58
【问题描述】:

我的代码可以打印出如下结果:

jobs = ['http://www.I-am-a-url.com','http://www.I-am-another-url.com']

当我调用变量TEXT 时,我想通过每个list-item 将这个列表保存在一个名为TEXTiterate 的变量中

我目前有:

TEXT = print('Latest jobs from site:\n\n{}'.format(job for job in jobs))

渴望

>>> TEXT
>>> 'Latest jobs from site: 'http://www.I-am-a-url.com', 'http://www.I-am-another-url.com'

这似乎不对,有人可以帮帮我吗?

【问题讨论】:

  • 使TEXT 成为一个函数。 TEXT = lambda: print('Latest jobs from site:\n\n{}'.format(job for job in jobs)) 然后将其称为 TEXT()
  • 在 Python 中打印返回 None
  • 如果您能解释一下“这似乎不正确”的意思,那将会有所帮助
  • 你想要的输出是什么?
  • 请在您的问题中准确显示所需的输出

标签: python list python-3.x iteration


【解决方案1】:

给定所需的输出,只需 join', ' 的列表:

print('Latest jobs from site: {}'.format(', '.join(jobs)))
# Latest jobs from site: http://www.I-am-a-url.com, http://www.I-am-another-url.com

【讨论】:

    【解决方案2】:

    我认为最简单的方法是构建一个每次调用时都会打印的函数。您已经很接近了,但是从生成器打印并不能完全按照您的预期工作。这样的东西效果更好

    TEXT = lambda: print(('Latest jobs from site:\n\n{}'*len(jobs)).format(*jobs))
    

    输出:

    Latest jobs from site:
    
    http://www.I-am-a-url.comLatest jobs from site:
    
    http://www.I-am-another-url.com
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2017-05-20
      • 2022-10-06
      相关资源
      最近更新 更多