所以我有这两个清单列表:
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上的所有list2 [0] [0]但只保留list1 [0] [3](在我的例子550中),如果你没有匹配list2 [0] [1] == list1 [0] [1](在我的例子中) user2 - 282不匹配)按原样获取该列表并仅将索引[4]修改为0(将变为如此:[' user2',282,' Mai 2017&# 39;,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]]
我如何达到我想要的输出?我使用的是python 3!谢谢!
答案 0 :(得分:0)
由于您似乎有结构化数据,我建议您创建类用户并使用对象进行操作。
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())
你会有更多可读的代码。
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)
答案 1 :(得分:0)
从示例中,我猜您将使用namedtuples,但解决方案基于列表理解:
desiredlist=[list2[0][:3]+[n2,list2[0][4]] if n1==list2[0][1]
else [id,n1,dates,n2,0] for id,n1,dates,n2,n3 in list1]
使用namedtuples你会有类似的东西:
from collections import namedtuple
Record=namedtuple("Record","Id n1 dates n2 n3")
Example1=Record('user1', 186, 'Feb 2017, Mar 2017, Apr 2017', 550, 555)
Example2=Record('user2', 282, 'Mai 2017', 3579, 3579)
Example3=Record('user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 0, 740)
list1=[Example1,Example2]
# Instead of creating a list of 1 element ( list2) I would rather compare it against the namedtuple directly
list2=Example3
# now the merging would look like this
desiredlist=[Record(*list2[:3],n2=i.n2,n3=list2.n3) if i.n1==list2.n1
else Record(*i[:4],n3=0) for i in list1]
# now desiredlist would look like:
[Record(Id='user1', n1=186, dates='Feb 2017, Mar 2017, Apr 2017, Mai 2017', n2=550, n3=740), Record(Id='user2', n1=282, dates='Mai 2017', n2=3579, n3=0)]
如果您不需要附加或更改每条记录的内容,它将使用namedtuples节省空间,它将帮助您保持记录更具可读性。否则你将不得不使用一个可变容器,无论是dict还是list