如何使用python为字符串列表中的每个字符串分配密钥



我有下面的列表,例如考虑:

my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']

我需要输出列表如下:

output = ['Rule:1,Key:ad,Message:help,Status:green','Rule:2,Key:bc,Message:quote,Status:green','Rule:3,Key:ef,Message:mask,Status:red','Rule:4,Key:ad,Message:help,Status:green']

以及如何遍历上面的列表,识别规则、密钥、消息和状态,并像下面的一样单独打印它们

Rule:1
Key:ad
Message:help
Status:green

需要帮助。

我尝试过以下方法:

for i in my_list:
for j in i:
output.append(j)

我需要输出列表如下:

解决方案

这个想法只是拆分每个字符串,然后相应地格式化输出字符串。

output = ["Rule:{},Key:{},Message:{},Status:{}".format(*s.split(',')) for s in my_list]

演示

my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']
output = ["Rule:{},Key:{},Message:{},Status:{}".format(*s.split(',')) for s in my_list]
print(output)
  • 输出

    ['Rule:1,Key:ad,Message:help,Status:green', 'Rule:2,Key:bc,Message:quote,Status:green', 'Rule:3,Key:ef,Message:mask,Status:red', 'Rule:4,Key:ad,Message:help,Status:green']
    

如何遍历上述列表

用于另一个问题

有不同的方法,这里有一个简单的

for line in output:
for entry in line.split(","):
[key,value] = entry.split(":")    # this is the traverse through

通过列表理解:

my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']
words = ['Rule', 'Key', 'Message', 'Status']
out = [','.join([':'.join(x) for x in zip(words, s.split(','))]) for s in my_list]

输出:

['Rule:1,Key:ad,Message:help,Status:green',
'Rule:2,Key:bc,Message:quote,Status:green',
'Rule:3,Key:ef,Message:mask,Status:red',
'Rule:4,Key:ad,Message:help,Status:green']

打印为多行

for s in my_list:
for x in zip(words, s.split(',')):
print(*x, sep=':')

输出:

Rule:1
Key:ad
Message:help
Status:green
Rule:2
Key:bc
Message:quote
Status:green
Rule:3
Key:ef
Message:mask
Status:red
Rule:4
Key:ad
Message:help
Status:green

相关内容

  • 没有找到相关文章

最新更新