Seems like there should be an easier way to do this:

header_line = [x for x in my_dict.keys()]
header_line.insert(0, "1st column\t2nd column")
header_line.append("note")
print "\t".join(map(str, header_line))

naively i thought the following should work, but get syntax error on the header_line:

header_line = ["1st column", "2nd column", x for x in my_dict.keys(), "note"] 
print "\t".join(map(str, header_line))
有帮助吗?

解决方案

How about

header_line = ['1st column', '2nd column'] + [x for x in my_dict.keys()] + ['note']

As mentioned in the comments, for this case you can just use my_dict.keys() or list(my_dict), but the above example is still useful as an example of how to do this when the list comprehension can't be trivially eliminated.

其他提示

You can use itertools.chain if you have a more generaty generator:

import itertools

print "\t".join(itertools.chain(["1st column", "2nd column"], my_dict, ["note"]))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top