问题描述
所以我有这2个列表列表:
So I have this 2 list of lists:
list1=[['user1', 186, 'Feb 2017, Mar 2017, Apr 2017', 550, 555], ['user2', 282, 'Mai 2017', 3579, 3579]]
list2=[['user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 0, 740]]
^^这只是一个示例,我将在其中包含更多列表,但原理和格式将相同.
^^ That is just a example, I will have more lists inside but the principle and format will be the same.
我将说明如何格式化所需的输出:当list2 [0] [1] == list1 [0] [1](在我的示例中为186 == 186)替换list1上的所有list2 [0] [0],但如果您没有匹配项list2 [0] [1] == list1 [0] [1](在我的示例中为user2-),则仅保留list1 [0] [3](在我的示例中为550) 282不匹配)按原样使用该列表,仅将index [4]修改为0(将变为:['user2',282,'Mai 2017',3579,0])
I will explain how I would like to format my desired output: when list2[0][1] ==list1[0][1] (in my example 186==186) replace all list2[0] on list1[0] but only keep list1[0][3] (in my example 550), if you don't have a match list2[0][1] ==list1[0][1] (in my example user2 - 282 isn't matched) take that list as it is and modify only index[4] to 0 (will become like this: ['user2', 282, 'Mai 2017', 3579, 0])
我将输入所需的输出,以便您更好地理解它:
I will put my desired output so you will understand it better:
desiredlist = [['user2', 282, 'Mai 2017', 3579, 0], ['user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 550, 740]]
我想拥有一个可以做到这一点的功能,我开始研究它,最后我做到了:
I would like to have a function that can do that, I started to work on it, and I ended with this:
def mergesafirmacheta(safir,macheta):
combined_list = macheta + safir
final_dict = {tuple(i[:2]):tuple(i[2:]) for i in combined_list}
merged_list = [list(k) + list (final_dict[k]) for k in final_dict]
return merged_list
但是,如果我打印出所需列表= mergesafirmacheta(list2,list1),我将会得到:
But if I print desiredlist = mergesafirmacheta(list2,list1) I will get:
[['user2', 282, 'Mai 2017', 3579, 3579], ['user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 0, 740]]
我如何获得所需的输出?我正在使用python 3!谢谢!
How I can get to my desired output?I'm using python 3! Thanks!
推荐答案
由于您似乎拥有结构化数据,因此我建议您创建类 User 并使用对象进行操作.
As you seem to have structured data, I would advise you to create class User and manipulate with objects.
class User:
def __init__(self, nick, id_, months, a, b):
self.nick = nick
self.id_ = id_
self.months = months
self.a = a
self.b = b
def __str__(self):
return "{self.nick}, {self.id_}, {self.months}, {self.a}, {self.b}".format(**locals())
您将拥有更具可读性的代码.
You would have much more readable code.
list1 = [
User('user1', 186, 'Feb 2017, Mar 2017, Apr 2017', 550, 555),
User('user2', 282, 'Mai 2017', 3579, 3579),
]
list2 = [
User('user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 0, 740),
]
for outdated in list1:
updateds = [u for u in list2 if outdated.id_ == u.id_]
if updateds:
outdated.nick = updateds[0].nick
outdated.months = updateds[0].months
outdated.b = updateds[0].b
else:
outdated.b = 0
for user in list1:
print(user)
这篇关于根据索引操作列表合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!