【问题标题】:Python 2.7 - make for loop print without new linePython 2.7 - 无需换行即可进行循环打印
【发布时间】:2017-05-18 08:55:54
【问题描述】:

我在 main_watch_images 列表中有两个项目,只想打印第一个。我试图在 findall 行之后添加 [0],但是它会垂直打印每个字母。我认为这是因为 for 循环将所有内容都打印在新行上,但我无法将其全部打印在一行上。

# Extract the first image (this is always the main image) that is in the
# "LIMITED" category
main_watch_images = findall('<img.* src="([^"]+).*LIMITED"', dennisov_html)
# Convert the URL to a full address
for images in main_watch_images:
    if images.startswith('/'):
        images = 'https://denissov.ru' + images 
    print images

请注意,这与其他问题不同。我是一个绝对的初学者,无法理解其他答案中使用的技术和操作符等。我需要一个具体的答案来解决我的问题。

【问题讨论】:

标签: python python-2.7 for-loop newline


【解决方案1】:

我在 main_watch_images 列表中有两个项目,我只想 打印第一个。

您可能正在寻找break

# Extract the first image (this is always the main image) that is in the
# "LIMITED" category
main_watch_images = findall('<img.* src="([^"]+).*LIMITED"', dennisov_html)
# Convert the URL to a full address
for images in main_watch_images:
    if images.startswith('/'):
        images = 'https://denissov.ru' + images
        print images
        break
    print images

编辑

是的,在这种情况下有效,但是可能有一个实例我想打印第二个,所以希望通过它们所在的位置打印列表中的项目,即 [0]、[1] 等。

尝试使用list

# Extract the first image (this is always the main image) that is in the
# "LIMITED" category
main_watch_images = findall('<img.* src="([^"]+).*LIMITED"', dennisov_html)
# Convert the URL to a full address
image_list = []
for images in main_watch_images:
    if images.startswith('/'):
        images = 'https://denissov.ru' + images
    image_list.append(images)

number_of_images_i_want_to_show = 1
for ctr in range(0,number_of_images_i_want_to_show):
    print(image_list[ctr])

【讨论】:

  • 啊是的,在这种情况下有效,但是可能有一个实例我想打印第二个,所以希望通过它们所在的位置打印列表中的项目,即 [0], [1] 等
  • 那么你应该在做任何其他事情之前将这些“图像”存储在一个集合中,即listimage_list.append('https://denissov.ru' + images) 那么你可以简单地做print image_list[0]
  • 是的 main_watch_images 是一个列表...但是我还需要那里的 if 语句来将域添加到缺少它的图像中,这是我知道如何使用 if 语句的唯一方法在for循环中
  • 谢谢你。老实说,我已经研究这个问题太久了,已经忘记了为什么我需要首先显示链接。在我重新评估我需要做的事情后不久,我将不得不回到它
  • 我建议您创建一个新问题,以免混淆其他人。如果此答案满足您当前的问题,请接受它作为关闭问题的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多