简体   繁体   English

python (boto3) 中的字符串到数组

[英]String to array in python (boto3)

I have a code that results in multiple string objects and I want to convert them into an array.我有一个导致多个字符串对象的代码,我想将它们转换成一个数组。 The end result looks like this最终结果看起来像这样

Queue1队列1

Queue2队列2

Queue3队列3

but, I need it like this但是,我需要这样

[Queue1, Queue2, Queue3] [队列1,队列2,队列3]

PS I am new to programming PS我是编程新手

import boto3
import numpy

rg = boto3.client('resource-groups')
cloudwatch = boto3.client('cloudwatch')

    
#def queuenames(rg):    
response = rg.list_group_resources(
    Group='env_prod'
)
resources = response.get('Resources')
for idents in resources:
    identifier = idents.get('Identifier')
    resourcetype = identifier.get('ResourceType')
    if resourcetype == 'AWS::SQS::Queue':
        RArn = identifier.get('ResourceArn')
        step0 = RArn.split(':')
        step1 = step0[5]
        print(step1)

To convert a string to a list do this:要将字符串转换为列表,请执行以下操作:

arr = 'Queue1 Queue2 Queue3'.split(' ')

# Result:
['Queue1', 'Queue2', 'Queue3']

You have a cycle where upon each step you print a string.您有一个循环,每一步都打印一个字符串。 Try creating an array before the cycle and adding each string inside the cycle, like this (I'm not fluent in Python, please excuse me if there is something wrong in the syntax)尝试在循环之前创建一个数组并在循环内添加每个字符串,就像这样(我对 Python 不太熟悉,如果语法有问题,请见谅)

import boto3
import numpy

rg = boto3.client('resource-groups')
cloudwatch = boto3.client('cloudwatch')

    
#def queuenames(rg):    
response = rg.list_group_resources(
    Group='env_prod'
)
resources = response.get('Resources')
myArray = []
for idents in resources:
    identifier = idents.get('Identifier')
    resourcetype = identifier.get('ResourceType')
    if resourcetype == 'AWS::SQS::Queue':
        RArn = identifier.get('ResourceArn')
        step0 = RArn.split(':')
        step1 = step0[5]
        print(step1)
        myArray.append(step1)

The code above will not change the way your output is displayed, but builds the array you need.上面的代码不会改变您的 output 的显示方式,但会构建您需要的数组。 You can remove the print line and print the array after the cycle instead.您可以删除打印线并在循环后打印数组。

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

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