の各項目(別の又は同一の)リストをリスト内の各アイテムを比較する処理は、数学的Cartesian productとして知られています。 Pythonはこれを行うための組み込み機能を有する:itertools.productためのループネストに相当する:
と仮定AとBがリストである:
:
for x in A:
for y in B:
print (x,y)
はとしてgenerator expressionと書くことができます。
for pair in ((x,y) for x in A for y in B):
print pair
または、より簡潔に:
from itertools import product
for pair in product(A, B):
print pair
あなたのケースでは、あなたがしていますリストのすべての項目をそれ自身と比較すると、product(texts, texts)
と書くことができますが、この場合、商品にはオプションのキーワード引数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))
本当にありがとうございました。ほんとうにありがとう!私はsimilarity()関数が浮動小数点を出力するので、round()を使用しています。 –
@Adam_G:なぜあなたは 'round()'を使用しているのか分かりますが、上記のように、 'round()'は出力フォーマットには使用されません。出力フォーマットの詳細については、Pythonチュートリアルの[Fancier Output Formatting](http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting)のセクションを参照してください。[浮動小数点演算:Issues and Limitations](http://docs.python.org/tutorial/floatingpoint.html)を参照してください。なぜなら、この目的のために 'round() 'を使うのは悪い考えです。 –