質問

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