문제

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