Python3 使用列表中对象的索引为变量赋值

Python3 assigning a value to variable using the index of an object inside a list

我正在尝试打印数组中的所有对象,而不是让用户选择其中一个对象。 通过输入,我想将该对象分配给一个变量。 这是我目前所拥有的:

# Call S3 to list current buckets
response = s3.list_buckets()
# Get a list of all bucket names from the response
buckets = [bucket['Name'] for bucket in response['Buckets']]
# Print out the bucket list
print('Bucket List:')
for number, bucket in enumerate(buckets):
    print(f'{number}. {bucket}')

# Which bucket will be used to put object
print('Which bucket should the object be placed?')
test_bucket_name = input('Enter bucket number: ')

我想从桶中获取值并将其分配给test_bucket_name

说明已评论。这应该可以帮助您入门


import boto3

s3_client = boto3.client('s3')

# Call S3 to list current buckets
response = s3_client.list_buckets()
# Get a list of all bucket names from the response
buckets = [bucket['Name'] for bucket in response['Buckets']]
# Print out the bucket list
print('Bucket List:')
for number, bucket in enumerate(buckets):
    print(f'{number}. {bucket}')

# Which bucket will be used to put object
print('Which bucket should the object be placed?')
test_bucket_number = input('Enter bucket number: ') # instead of test_bucket_name, test_bucket_number
print(test_bucket_number) 
try:
    # Index the list of buckets with the number they picked, cast to int to make sure their selection was a valid number
    selected_bucket = buckets[int(test_bucket_number)] 
    print(selected_bucket)
except ValueError as e:
    print(e)
    # Do something to ask the user to pick a number again. Their selection wasn't a number