Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - print tab delimited two-word set

Tags:

python

I have a set of words such as this:

mike dc car dc george dc jerry dc

Each word, mike dc george dc is separated by a space. How can I create a two-word set and separate the two-word set by a tab? I would like to print it to the standard output stdout.

EDIT I tried using this: print '\t'.join(hypoth), but it doesn't really cut it. All the words here are just tab delimited. I would ideally like the first two words separated by a space and each two word-set tab delimited.

like image 881
Eagle Avatar asked Feb 13 '23 23:02

Eagle


1 Answers

Assuming you have

two_word_sets = ["mike dc", "car dc", "george dc", "jerry dc"]

use

print "\t".join(two_word_sets)

or, for Python 3:

print("\t".join(two_word_sets))

to print the tab-separated list to stdout.

If you only have

mystr = "mike dc car dc george dc jerry dc"

you can calculate a as follows:

words = mystr.split()
two_word_sets = [" ".join(tup) for tup in zip(words[::2], words[1::2])]

This might look a bit complicated, but note that zip(a_proto[::2], a_proto[1::2]) is just [('mike', 'dc'), ('car', 'dc'), ('george', 'dc'), ('jerry', 'dc')]. The rest of the list comprehension joins these together with a space.

Note that for very long lists/input strings you would use izip from [itertools], because zip actually creates a list of tuples whereas izip returns a generator.

like image 66
Uli Köhler Avatar answered Feb 28 '23 00:02

Uli Köhler