我有两张单子:
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]]
^^^这只是一个例子,我会有更多的清单内,但原则和格式将是相同的。你知道吗
我将解释如何格式化我想要的输出:当list2[0][1]==list1[0][1](在我的示例中186==186)替换list1[0]上的所有list2[0],但只保留list1[0][3](在我的示例550中),如果没有匹配的list2[0][1]==list1[0][1](在我的示例中user2-282不匹配),则将该列表保持原样,只将索引[4]修改为0(将变成这样:['user2',282,'Mai 2017',3579,0])
我会把我想要的输出,让你更好地理解它:
desiredlist = [['user2', 282, 'Mai 2017', 3579, 0], ['user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 550, 740]]
我想有一个函数可以做到这一点,我开始研究它,并以以下内容结束:
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
但是如果我打印desiredlist=mergesafirmacheta(list2,list1),我将得到:
[['user2', 282, 'Mai 2017', 3579, 3579], ['user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 0, 740]]
我怎样才能得到我想要的结果?我在用Python3!谢谢!你知道吗
从这个示例中,我猜您将受益于使用namedtuples,但是解决方案是基于列表理解的:
使用namedtuples,您可以得到如下结果:
如果您不需要附加或更改每个记录的内容,它将使用namedtuples节省空间,并帮助您保持记录的可读性。否则,您将不得不使用可变容器,无论是dict还是list
由于您似乎拥有结构化数据,我建议您创建classUser并使用对象进行操作。你知道吗
你会有更可读的代码。你知道吗
相关问题 更多 >
编程相关推荐