0

I am iterating over a list in a scripting language, here using python.

Say, I want to generate the string "list(), list(), list()".

Something gets added to the brackets of "list(....)" but that's not important.

I need to treat the first Element differently, as I don't add a comma (",") before the word list then.

My Code:

mydict = {"r": 34, "i": 56, "k" : 99} 

s = ""

listOfKeys = list()



firstInList = True

for key, value in mydict.iteritems() :

    listOfKeys.append(key)

    if firstInList:
       firstInList = False
    else:
       s += ","

    s += "list("

    # 
    # more code that is not relevant to the question ...
    #

    s += ")"

print s

Now when I have nested lists the approach gets messy. How do I solve that better in python?

4

2 回答 2

4

如果您只是将您的项目保存在一个列表中,那么您可以做','.join(items)正确的事情。

于 2013-10-28T17:33:21.347 回答
0

通常,您只需加入即可。

",".join(listOfValues)

您可以轻松地构建一个值列表,然后对其执行此操作,以创建逗号分隔的字符串。但是,如果您想继续这样做,您可以在附加之前检查字符串是否为空。

于 2013-10-28T17:34:08.430 回答