python如何打印表_Python中的打印表
將列表中的每個項與(另一個或同一個)列表中的每個項進行比較的過程在數學上稱為Cartesian product。Python有一個內置函數來完成這個任務:itertools.product它相當于嵌套for循環(huán):
假設A和B是列表:for x in A:
for y in B:
print (x,y)
或者,更簡潔地說:from itertools import product
for pair in product(A, B):
print pair
在您的例子中,您將一個列表的所有項與其自身進行比較,因此您可以編寫product(texts, texts),但是product在本例中有可選的關鍵字參數repeat:product(A, repeat=4)的意思與product(A, A, A, A)相同。在
現在可以這樣重寫代碼:from itertools import product
caesar = """BOOK I
I.--All Gaul is divided into three parts, one of which the Belgae
inhabit, the Aquitani another, those who in their own language are
called Celts, in ours Gauls, the third. All these differ from each other
in language, customs and laws."""
hamlet = """Who's there?"
"Nay, answer me. Stand and unfold yourself."
"Long live the King!"
"Barnardo!"
"He." (I.i.1-5)"""
macbeth = """ACT I SCENE I A desert place. Thunder and lightning.
[Thunder and lightning. Enter three Witches]
First Witch When shall we three meet again
In thunder, lightning, or in rain?
Second Witch When the hurlyburly's done,
When the battle's lost and won."""
texts = [caesar, hamlet, macbeth]
def similarity(x, y):
"""similarity based on length of the text,
substitute with similarity function from Natural Language Toolkit"""
return float(len(x))/len(y)
for pair in product(texts, repeat=2):
print "{}".format(similarity(*pair))
總結
以上是生活随笔為你收集整理的python如何打印表_Python中的打印表的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: step 文件在sw怎么编辑_Solid
- 下一篇: 舟迁中英文朗读器 v1.1 是什么
