Question

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))
Était-ce utile?

La solution

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.

Autres conseils

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"]))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top