1

I have a - probably - trivial question that's been bugging me for some time and I still haven't found an answer. Many of my scripts read some files, compare values from them and save these in a list or dictionary from which I then write an output file of some sort. What I always do is, I loop over the list and write the single items to my output, separated by a tab, comma, or line break. What I am always wondering is how I can prevent a separator appearing after the last item on my list has been printed.

Here is an example:

dict1 = {a: [1,2,3], b: [4,5,6], c: [7,8,9]}
for key in dict1:
    outfile.write(key +": ")
    for item in dict1[key]:
        outfile.write(str(item) +", ")
    outfile.write("\n")

The output would then look like this:

a: 1, 2, 3, 
b: 4, 5, 6, 
c: 7, 8, 9, 

How do I avoid that last ", "?

4

2 回答 2

3

使用str.join方法和列表理解:

for key, value in dict1.iteritems():
    outfile.write(key +": ")
    outfile.write(', '.join([str(item) for item in value]))
    outfile.write("\n")
于 2013-03-04T13:59:48.027 回答
1

使用标准库CSV模块怎么样?

它会处理这个问题,加上任何必要的转义符(如果您的值之一包含逗号怎么办?)

(然后,当然,作为一般情况,使用string.join(list)正确连接没有尾随分隔符)

于 2013-03-04T14:02:44.030 回答