比较字典/列表

时间:2020-02-08 07:47:12

标签: python list

我在完成需要完成的任务时遇到了麻烦,它是关于比较和打印已经给出的两个不同列表的相似性。 问题是,当我运行它时,会出现错误并显示: 字典更新序列元素#0的长度为7; 2是必需的

english.txt内容为: 圈 表 年 竞争 french.txt读取: 比恩 竞争 怜悯 空气 桌子

这是我的代码:

a = open('english.txt').readlines()
b = open('french.txt').readlines()
a2 = dict(b)
b2 = dict(a)
result = a2.intersection(b2)
print(a2, b2)

2 个答案:

答案 0 :(得分:1)

问题是您需要使用列表时正在使用字典。

字典具有以下结构:{“ key1”:“ value1”,“ key2”:“ value2”}

列表具有以下结构:[“ value1”,“ value2”]

错误表明它正在指定2个值的序列(键和值),但接收到7个值的序列(“ circ \ n”)。这就是python正在读取的内容。

#In english.txt

circle\n
table\n
year\n
competition

另一个文件中的内容。

#In french.txt

bien\n
competition\n
merci\n
air\n
table

您需要将dict替换为list并删除行尾字符

#This function removes \n character
def processLine(line):
  return line.replace('\n', '')

a = open('english.txt').readlines()          #Read english.txt
e = list([processLine(line) for line in a])  #Create a list where every line in the file is processed
#e = ['circle', 'table', 'year', 'competition']

b = open('french.txt').readlines()           #Read french.txt
f = list([processLine(line) for line in b])  #Create a list where every line in the file is processed
#f = ['bien', 'competition', 'merci', 'air', 'table']

intersection = list(set(e) & set(f))
#intersection = ['table', 'competition']

答案 1 :(得分:0)

我认为,对于dict数据结构,您需要传递两个值;一个用于key,另一个用于value与密钥相关联。

例如:

d = {'a':'apple', 'b':'banana'}

编辑: 如果ab是单词列表,则

a = "circle table year competition".split()
b = "bien competition merci air table".split()
com_words = list(set(a) & set(b))