Skip to main content
 首页 » 编程设计

python之如何从列表中创建单词对列表

2025年05月04日13telwanggs

我在文件“temp”中有一个单词列表:

 1. the  
 2. of 
 3. to 
 4. and 
 5. bank 

等等

我如何提高它的可读性?

import itertools 
f = open("temp.txt","r") 
lines = f.readlines() 
pairs = list(itertools.permutations(lines, 2)) 
print(pairs) 

我迷路了,请帮忙

请您参考如下方法:

import itertools 
 
with open("temp.txt", "r") as f: 
    words = [item.split(' ')[-1].strip() for item in f] 
 
pairs = list(itertools.permutations(words, 2)) 
print(pairs) 

打印(使用 pprint 提高可读性):

[('the', 'of'), 
 ('the', 'to'), 
 ('the', 'and'), 
 ('the', 'bank'), 
 ('of', 'the'), 
 ('of', 'to'), 
 ('of', 'and'), 
 ('of', 'bank'), 
 ('to', 'the'), 
 ('to', 'of'), 
 ('to', 'and'), 
 ('to', 'bank'), 
 ('and', 'the'), 
 ('and', 'of'), 
 ('and', 'to'), 
 ('and', 'bank'), 
 ('bank', 'the'), 
 ('bank', 'of'), 
 ('bank', 'to'), 
 ('bank', 'and')]