系统输出两个类型为string的变量; op1如下,
{"fname":"John","mname":"Smith","ID":"2711"}
{"fname":"Nick","mname":"Bart","ID":"3011"}
{"fname":"Nash","mname":"willy","ID":"2811"}
{"fname":"Jack","mname":"Tuna","ID":"2911"}
{"fname":"Peter","mname":"Jill","ID":"2611"}
{"fname":"Aaron","mname":"Sane","ID":"3111"}
和op2如下,
{"fname":"John","mname":"Smith","Age":"Berkley"}
{"fname":"Nash","mname":"willy","Age":"Godson"}
{"fname":"Jack","mname":"Tuna","Age":"Welch"}
我将这些值复制到2个文本文件op1.txt和op2.txt中;我想创建第三个变量(文本文件),该变量仅包含名字和姓氏在op2中存在的ID。请注意,只有2个标记是通用的,即fname
和lname
。
基于上述输入的输出必须为 [2711,2811,2911]
有没有办法避免将其写入文件并在变量级别本身进行比较?
答案 0 :(得分:0)
您应该使用2个列表进行2次循环:
a = [
{"fname":"John","lname":"Smith","ID":"2711"},
{"fname":"Nick","lname":"Bart","ID":"3011"},
{"fname":"Nash","lname":"willy","ID":"2811"},
{"fname":"Jack","lname":"Tuna","ID":"2911"},
{"fname":"Peter","lname":"Jill","ID":"2611"},
{"fname":"Aaron","lname":"Sane","ID":"3111"}
]
b = [
{"fname":"John","lname":"Smith","Age":"Berkley"},
{"fname":"Nash","lname":"willy","Age":"Godson"},
{"fname":"Jack","lname":"Tuna","Age":"Welch"},
{"fname":"FakeJill","lname":"FakeJill","Age":"FakeJill"},
{"fname":"FakeJack","lname":"FakeJack","Age":"FakeJack"}
]
c = []
,然后在此处循环显示字典列表:
for itema in a:
for itemb in b:
if itema['fname'] == itemb['fname'] and itema['lname'] == itemb['lname'] :
c.append(int(itema['ID']))
print(c)
结果将是这样的: [2711,2811,2911]