我有两个带有一些数据的Python列表:
list_first = [(1, 2, 'Adam', 'Men', '3.5', '1'),
(1, 2, 'Ewa', 'Women', '2', '1'),
(1, 2, 'Adam', 'Men', '4', '2')]
second_list = [(2, 5, 'Jack', 'Men', '3.5', '1'),
(1, 3, 'Chris', 'Women', '5', '2'),
(10, 22, 'Adam', 'Men', '42', '11')]
现在我想在second_list
中找到重复项,但只能找到名称和性别字段,所以在上面的例子中:
second_list
中的副本是Adam。 (亚当,男人)。
现在我希望将此元组((1, 2, 'Adam', 'Man', '4', '2'))
移至list_first
。
我尝试按以下方式制作: (没有成功):
name_fy = [(item[2] for item in list_first) and
(item[3] for item in list_first)]
name_sy = [(item[2] for item in list_second) and
(item[3] for item in list_second)]
for i in name_fy :
for j in name_sy :
if i == j:
# move to list_first
答案 0 :(得分:1)
您可以对any
使用单个列表理解:
list_first = [(1, 2, 'Adam', 'Men', '3.5', '1'), (1, 2, 'Ewa', 'Women', '2', '1'), (1, 2, 'Adam', 'Man', '4', '2')]
second_list = [(2, 5, 'Jack', 'Men', '3.5', '1'), (1, 3, 'Chris', 'Women', '5', '2'), (10, 22, 'Adam', 'Man', '42', '11')]
list_first += [i for i in second_list if any(x[2] == i[2] and x[3] == i[3] for x in list_first)]
second_list = list(filter(lambda x:not any(a[2] == x[2] and a[3] == x[3] for a in list_first), second_list))
输出:
[(1, 2, 'Adam', 'Men', '3.5', '1'), (1, 2, 'Ewa', 'Women', '2', '1'), (1, 2, 'Adam', 'Man', '4', '2'), (10, 22, 'Adam', 'Man', '42', '11')]
[(2, 5, 'Jack', 'Men', '3.5', '1'), (1, 3, 'Chris', 'Women', '5', '2')]