gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:53 25 4
gpt4 key购买 nike

我在文件“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')]

关于python - 如何从列表中创建单词对列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com