[英]Difference between two list
I have the following text file: 我有以下文本文件:
text1 text2
# text2 text3 text4
# text5 text4 text6
text 3 text 4
# ....
...
I would like to have a array list like the following, where fu 我想有一个像下面这样的数组列表
dict[function([text1, text2])] = [[text2, text3, text4], [text5, text4, text6]].
The idea is to open the file, read line by line 想法是打开文件,逐行读取
dict = {}
inputfile = open("text.txt","r")
for line in inputfile:
l=line.split()
if not line.startswith("#"):
#create a new key
else:
dict[key] = l
However, the problem is that I cannot assign other element if I go to the next line. 但是,问题是,如果我转到下一行,则无法分配其他元素。 Do you know how to solve this issue?
你知道如何解决这个问题吗?
"Function"is just a function which I defined elsewhere and that takes as an input a list of strings. “函数”只是我在其他地方定义的函数,它以字符串列表作为输入。
You can use collections.defaultdict
to create a dictionary with list
s as the values to which you can append items. 您可以使用
collections.defaultdict
创建一个以list
s为值的字典,您可以在其中附加项目。
from collections import defaultdict
my_dict = defaultdict(list)
with open('text.txt') as f:
key = ''
for line in f:
if not line.startswith('#'):
key = line
# key = function(line.split())
continue
my_dict[key].append(line.strip('#').split())
print(my_dict)
Output: 输出:
defaultdict(<class 'list'>,
{'text1 text2\n': [['text2', 'text3', 'text4'],
['text5', 'text4', 'text6']],
'text3 text4\n': [['text21', 'text31', 'text41'],
['text51', 'text41', 'text61']]})
Just change the key = line
line to whatever function you're passing the key to. 只需将
key = line
line更改为您要将密钥传递给的任何函数。
My text.txt
file contains: 我的
text.txt
文件包含:
text1 text2
# text2 text3 text4
# text5 text4 text6
text3 text4
# text21 text31 text41
# text51 text41 text61
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.