Python比较两个对象列表并追加到一个列表

时间:2018-09-18 11:41:16

标签: python python-3.x

我正在尝试比较两个对象列表,以查看两个列表中的人名是否匹配。

list1 = ('Name', 'Kilometers Driven')
list1 example = ('John Doe', 500),('Jane Doe', 200)

list2 = ('Id','Name','Kilometers Walked','Total Events')
list2 example = (2,'Joe Doe',20,2),(3,'Frank Kelly',32,4)

如果此人同时出现在两个列表中,我想选择“行驶的公里数”并将其添加到该人的第二个列表中。

感谢您的帮助

4 个答案:

答案 0 :(得分:2)

我个人认为dict更适合您的解决方案,因为您可以通过它们的键(例如dict ['km_driven'])访问它们,而这些键比列表中的整数索引更容易混淆。

此代码使用列表起作用:

# list1 = ('Name', 'Kilometers Driven')
list1 = [('Joe Doe', 500),('Jane Doe', 200)]

# list2 = ('Id','Name','Kilometers Walked','Total Events', optional='Kilometers Driven')
list2 = [(2,'Joe Doe',20,2),(3,'Frank Kelly',32,4)]

# Iterate through items of list1
for item1 in list1:
    # Iterate through items of list2
    for i in range(len(list2)):
        # Match 'Name' field in list1 to 'Name' field in list2
        if item1[0] == list2[i][1]:
            # Add 'Kilometers Driven' to that list2 item
            list2[i] = list2[i] + (item1[1], )

print(list2[0])     

输出:

(2, 'Joe Doe', 20, 2, 500)

答案 1 :(得分:1)

给出数据列表: (list1和list 2是元组的列表。)

list1 = [ ('John Doe', 500), ('Jane Doe', 200) ]

list2 = [ (2,'John Doe',20,2), (3,'Frank Kelly',32,4) ]

for i in list1:
  name,km=i #unpacking tuple into name and km driven
  for index,j in enumerate(list2): #iterate list2 with index
   if name in j: # if name exists in element j of list2
     two[index]=two[idx]+(km,) #add km driven to element j

for循环后的list2的值:

[(2, 'John Doe', 20, 2, 500), (3, 'Frank Kelly', 32, 4)]

答案 2 :(得分:0)

字典将使您的任务更加轻松。 这是一个例子。

dict1 = {'John Doe': 500, 'Jane Doe': 200}
dict2 = {'Joe Doe': [20, 2],'John Doe': [30, 3]}
for k, v in dict1.items():
    if k in dict2.keys():
        dict2[k][0]+=v

答案 3 :(得分:0)

我使用了python的namedtuple。

示例代码:

from collections import namedtuple

Type_1 = namedtuple('Type_1', 'Name Kilometers_Driven')
list_1 = [Type_1('John Doe', 500), Type_1('Jane Doe', 500)]


Type_2 = namedtuple('Type_2', 'Id Name Kilometers_Walked Total_Events')
list_2 = [Type_2(2, 'Joe Doe', 20, 2),
          Type_2(3, 'Frank Kelly', 32, 4),
          Type_2(3, 'John Doe', 10, 3)]

for obj_1 in list_1:
   for idx, obj_2 in enumerate(list_2):
       if obj_1.Name == obj_2.Name:
           total = obj_2.Kilometers_Walked + obj_1.Kilometers_Driven
           list_2[idx] = obj_2._replace(Kilometers_Walked = total)

print(list_1)
print(list_2)

[Type_1(Name ='John Doe',Kilometers_Driven = 500),Type_1(Name ='Jane Doe',Kilometers_Driven = 500)]

[Type_2(Id = 2,Name ='Joe Doe',Kilometers_Walked = 20,Total_Events = 2),Type_2(Id = 3,Name ='Frank Kelly',Kilometers_Walked = 32,Total_Events = 4),Type_2( Id = 3,姓名=“ John Doe”,公里数= 510 ,Total_Events = 3)]

如您所见,公里数正在正确更新