简体   繁体   中英

How to extract values from list to add to another list in python

I have the following code:

items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])

response['Contents'] has a schema like this:

{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner': 
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...] .

How can I extract the values correctly? (I'll be using zip with another list that has column names to create a dict later).

Just append them as a list / tuple to your original list:

items = []
for i in response['Contents']:  # assuming response['Contents'] is a list
    items.append([
        's3://' + response['Name'] + '/' + i['Key'],
        i['Key'].rsplit('/', 1)[-1],
        i['Size']
    ])

First off, you can't do items[i].append() because i is a dict and items is a list (among other reasons). Perhaps you should consider making a new list inside your for loop, appending each item, and then converting it into a tuple to append to items:

items = list()
for contents in response['Contents']:
    i = list()
    i.append('s3://' + response['Name'] + '/' + contents['Key'])
    i.append(contents['Key'].rsplit('/', 1)[-1])
    i.append(contents['Size'])
    items.append(tuple(i))

As this question is open I'm gonna give my take: I'd write it as this:

import os

items = []
s1 = 's3://{Name}/{{Key}}'.format(**response)

for i in response['Contents']:  

    v1 = s1.format(name,**i)
    v2 = os.path.basename(i['Key'])
    v3 = i['Size']    

    items.append([v1,v2,v3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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