Python - 打印制表符分隔的两字集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21371846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - print tab delimited two-word set
提问by Eagle
I have a set of words such as this:
我有一组这样的词:
mike dc car dc george dc jerry dc
Each word, mike dc george dcis 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.
每个单词,mike dc george dc由一个空格分隔。如何创建两个词集并通过制表符分隔两个词集?我想将它打印到标准输出stdout。
EDITI 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.
编辑我尝试使用这个:
print '\t'.join(hypoth),但它并没有真正削减它。这里的所有单词都只是制表符分隔。理想情况下,我希望前两个单词用空格分隔,每两个单词集制表符分隔。
采纳答案by Uli K?hler
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:
或者,对于 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:
您可以按如下方式计算 a:
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.
这可能看起来有点复杂,但请注意,这zip(a_proto[::2], a_proto[1::2])只是[('mike', 'dc'), ('car', 'dc'), ('george', 'dc'), ('jerry', 'dc')]. 列表推导式的其余部分用空格将它们连接在一起。
Note that for very long lists/input strings you would use izipfrom [itertools], because zipactually creates a list of tuples whereas izipreturns a generator.
请注意,对于很长的列表/输入字符串,您将使用izip[ itertools],因为zip实际上创建了一个元组列表,而izip返回了一个生成器。
回答by Kevin
You can do this in 1-2 lines, but it is easiest to read if you break it up:
您可以在 1-2 行中完成此操作,但如果将其拆分,则最容易阅读:
words = "mike dc car dc george dc jerry dc"
wlist = words.split()
mystr = ""
for i in range(0, len(wlist), 2):
mystr = "%s%s %s\t" % (mystr, wlist[i], wlist[i+1])
print mystr

