python3.x - python二維數組
問題描述
texts = [[word for word in document.lower().split()] for document in documents]
我在網址我愛自然語言處理-如何計算兩個文檔的相似度(二)中看到下面一份代碼。對于>>> texts = [[word for word in document.lower().split()] for document in documents]的含義不是很理解。
>>>documents = ['Shipment of gold damaged in a fire',... 'Delivery of silver arrived in a silver truck',... 'Shipment of gold arrived in a truck']>>> texts = [[word for word in document.lower().split()] for document in documents]>>> print texts[[’shipment’, ’of’, ’gold’, ’damaged’, ’in’, ’a’, ’fire’], [’delivery’, ’of’, ’silver’, ’arrived’, ’in’, ’a’, ’silver’, ’truck’], [’shipment’, ’of’, ’gold’, ’arrived’, ’in’, ’a’, ’truck’]]
對于一般的for var in list:這種形式,我是知道的。但是上面的那種二維數組,我就不是很理解為什么了。求助,幫忙分析一下
問題解答
回答1:這個語法叫 “List Comprehensions”先將https://docs.python.org/2/tut...文檔的例子過一遍,就會明白怎么回事的。
回答2:python中創建一個二維數組的方法例如創建一個3*3的數組方法1 直接定義
[py]matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]][/py]
方法2 間接定義
matrix = [[0 for i in range(3)] for i in range(3)]
一種方法而已,.lower().split()是處理文件里面的單詞,大寫邊小寫,分割開。
相關文章:
1. javascript - ionic1的插件如何遷移到ionic2的項目中2. java - 如何在Fragment中調用Activity的onNewIntent?3. javascript - h5上的手機號默認沒有識別4. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat5. css - 關于input標簽disabled問題6. python - 獲取到的數據生成新的mysql表7. 怎么用css截取字符?8. window下mysql中文亂碼怎么解決??9. javascript - jquery hide()方法無效10. python的文件讀寫問題?
