我正在尝试以字典格式比较两组数据 (file1,file2)。使用示例 1(见下文)进行比较时,代码有效,但当我添加更多数据(示例 2)时,出现错误,因为 元组索引必须为整数或切片。我正在努力理解这一点,因为我正在比较两组字典而不是列表来使用整数来比较使用索引中的整数而不是字典中的键名。
#Dict list 示例 1:使用此示例,它有效
file1= {'name': 'Phill', 'age': 42}
file2= {'name': 'Phill', 'age': 22}
#Dict list 示例 2:对于这个示例,它不起作用
file1= {'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}
file2= {'name': 'Phill', 'age': 22},{'name': 'Phill', 'age': 52}
#Function with two args
def diffValue (file1,file2) :
for newAge in file1,file2 :
if file1 [ 'age' ] == file2 [ 'age' ] :
# if no difference found in both files within the age field
print ( "No difference found" )
else :
# the age is different. return values name,age where ever there is a difference from file1 only
return newAge
预期结果:
Return {'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}
答案 0 :(得分:0)
>>> file1= {'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}
>>> file1
({'name': 'Phill', 'age': 42}, {'name': 'Phill', 'age': 22})
>>> type(file1)
<class 'tuple'>
file1 是元组,这就是它给出错误的原因
让它与您的函数一起工作的一种方法是:
def diffValue (file1,file2) :
for newAge in file1,file2 :
if file1 [ 'age' ] == file2 [ 'age' ] :
# if no difference found in both files within the age field
print ( "No difference found" )
else :
# the age is different. return values name,age where ever there is a difference from file1 only
return newAge
file1= [{'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}]
file2= [{'name': 'Phill', 'age': 22},{'name': 'Phill', 'age': 52}]
a=""
for i in range(len(file1)):
a+=str(diffValue(file1[i],file2[i]))+","
a=a[:-1]
print(a)
答案 1 :(得分:0)
我认为您打算这样做:
file1 = {'name': 'Phill', 'age': 42}, {'name': 'Phill', 'age': 22}
file2 = {'name': 'Phill', 'age': 22}, {'name': 'Phill', 'age': 52}
def diff_value(f1, f2):
# Create a list to store the differences
diffs = []
# Iterate for every element in parallel
for v1, v2 in zip(f1, f2):
if v1['age'] == v2['age']:
# If no difference found in both files within the age field
print('No difference found')
else:
# The age is different, append v1 to `diffs`
diffs.append(v1)
return diffs
print(diff_value(file1, file2))
# Output: [{'name': 'Phill', 'age': 42}, {'name': 'Phill', 'age': 22}]