Python从for循环中的最后一行删除逗号

时间:2017-07-24 13:08:54

标签: python

我想知道如何从python中的for循环中的最后一行删除逗号。当我运行脚本时,它给我下面的输出(在代码部分之后)。我想删除第四行“{”{#MACRO}“:”queue4“}末尾的逗号,”请有人帮忙吗?

顺便说一句,如果有更好的方法来构建块,请分享想法。我是初学者,喜欢学习。 :)

代码:

import json
import urllib
import string

Url= "http://guest:guest@localhost:55672/api/queues"
Response = urllib.urlopen(Url)
Data = Response.read()

def Qlist(Name):
    Text = '''    {{"{{#MACRO}}":"{Name}"}},'''.format(Name=Name)
    print Text

X_json = json.loads(Data)

print '''{
"data":['''
for i in X_json:
    VV = i['name']
    Qlist(VV)
print ''']
}'''

以下是输出:

{
"data":[
    {"{#MACRO}":"queue1"},
    {"{#MACRO}":"queue2"},
    {"{#MACRO}":"queue3"},
    {"{#MACRO}":"queue4"},
]
}

非常感谢

2 个答案:

答案 0 :(得分:4)

您可以按如下方式修改循环。

# Create and initialize a dictionary (Associative Array)
# data['data'] is an empty list.
# Variable name (data in this case) can be anything you want.
# 'data' is a key. notice the quotations around. it's not a variable.
# I used 'data' as the key, becasue you wanted your final output to include that part.
data = {"data": []}

for i in X_json:

   # We are not calling the data dictionary here.
   # We are accessing the empty list we have created inside the `data` dict (above) using data['data'] syntax.
   # We can use the append function to add an item to a list.
   # We create a new dictionary for every `name` item found in your json array and 
   #  append that new dictionary to the data['data'] list.
   data['data'].append({"{#MACRO}": i['name']})

print(json.dumps(data))
# or print json.dumps(data, indent=True)

详细了解json.dumps() here。您可以阅读有关python' listdictionary here

的更多信息

答案 1 :(得分:-1)

printQlist - 而不是return一个值;然后,您可以使用逗号作为分隔符加入所有返回的值:

def Qlist(Name):
    Text = '''    {{"{{#MACRO}}":"{Name}"}}'''.format(Name=Name)
    return Text

print '''{
"data":[''' +
',\n'.join([ Qlist(i['name']) for i in X_json ]) + 
''']
}'''

无论如何,使用json.dumps可能是一个更好的主意。