简体   繁体   English

Python列表理解仅返回最后一项

[英]Python list comprehension returning only last item

I am trying to post multiple files using requests post. 我正在尝试使用请求发布来发布多个文件。

The format that is stated here is: 此处说明的格式为:

>>> url = 'http://httpbin.org/post'
>>> multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
                      ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
>>> r = requests.post(url, files=multiple_files)
>>> r.text

So I am trying to do this with a list comprehension. 因此,我试图通过列表理解来做到这一点。 But only the last image is uploading. 但只有最后一张图像正在上传。 I have a feeling that the comprehension is overriding the images since all images have the same name ' visuals '. 我的理解是理解力会覆盖图像,因为所有图像都具有相同的名称“ visuals ”。 But I required all of them to have the name ' visuals '. 但是我要求所有这些人都必须使用“ visuals ”这个名称。

images=[list of image URLS]
files=[('visuals',(str(index)+'.jpg',requests.get(image).content,'image/jpeg')) for index,image in enumerate(images)]
requests.post(script.php,files=files)

For example, if there are 20 images, only 20.jpg is sent to my script.php . 例如,如果有20张图像,则只有20.jpg发送到我的script.php中

Response to answer (not working): 回答答案(无效):

  images=response.xpath(root+'/photos//url/text()').extract()
  visuals=[(str(index)+'.jpg',requests.get(image).content,'image/jpeg') for index,image in enumerate(images)]
  requests.post(triggers,data={'json':json.dumps(array)},files={'visuals':visuals})

The files argument to requests.post is supposed to be a dict . files参数requests.post应该是一个dict See the example here . 请参阅此处的示例。 Since you pass it with a list object, it will be casted internally to a dict object. 由于您将其与list对象一起传递,因此它将在内部强制转换为dict对象。 During the type casting, a latter element will overwrite the former element with the same key value! 在类型转换期间,后一个元素将使用相同的键值覆盖前一个元素! Since all element in has the same key "visuals", only the last one will remain in the final dict object. 由于其中的所有元素都具有相同的键“视觉效果”,因此只有最后一个元素将保留在最终的dict对象中。

This question was already answered in requests' issue page #737 . 请求的问题页面#737中已经回答了这个问题。

The list of tuples you provided to data has dict() called on it. 您提供给数据的元组列表已调用dict()。 Dictionaries (obviously) don't allow duplicate keys, but your list of tuples has duplicate keys, so the last item in the iterable takes the value for that key ... so I'd assume that this is intended behaviour. 字典(显然)不允许重复的键,但是您的元组列表具有重复的键,因此iterable中的最后一项采用该键的值...因此,我假设这是预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM