<p>一种方法是按它们的<code>name</code>&;<code>direction</code>对所有总线进行分组。然后合并数据,确保“早”时间在<code>'timeLeft'</code>,晚”时间在<code>'timeNext'</code>:</p>
<p>Doku:<a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">itertools.groupby</a></p>
<pre><code>busses = [
{
"name": "Bus 60",
"direction": "City",
"timeLeft": "1",
"timeNext": ""
},
{
"name": "Bus 60",
"direction": "City",
"timeLeft": "3",
"timeNext": ""
},
{
"name": "Bus 21",
"direction": "City",
"timeLeft": "5",
"timeNext": ""
},
]
from itertools import groupby
def mergeBusses(listOfBussesDict):
sortList = sorted(listOfBussesDict, key=lambda x: (x["name"],x["direction"]))
# we use name + direction as key for the grouping
merged = groupby(sortList, lambda x: (x["name"],x["direction"]))
# you might consider cleaning up the keys that are used:
# merged = groupby(sortList, lambda x: (x["name"].strip(),x["direction"].strip()))
# if your source data is bad.
for k,g in merged:
sameBus = list(g)
# now we take all times and sort them by their integer value to
# update the correct slots in the dictionary
times = sorted([x["timeLeft"] for x in sameBus],key= lambda y:int(y))
if len(times)>1:
# we only need to do this if the grouping has > 1 bus, in that
# case we use the basedata of the first bus and adjust the times
sameBus[0]["timeLeft"] = times[0]
sameBus[0]["timeNext"] = times[1]
# we just yield the first bus from the group which now has correct times
yield sameBus[0]
# need to make a list from our generator result
mergedOnes = list(mergeBusses(busses))
print(mergedOnes)
</code></pre>
<p>输出:</p>
<pre><code>[{'name': 'Bus 60', 'direction': 'City', 'timeLeft': '1', 'timeNext': '3'},
{'name': 'Bus 21', 'direction': 'City', 'timeLeft': '5', 'timeNext': ''}]
</code></pre>
<p>您编辑的示例将导致:</p>
<pre><code>[{'name': 'Bus 60', 'direction': 'City', 'timeLeft': '1', 'timeNext': '3'},
{'name': 'Bus 1', 'direction': 'Some Place', 'timeLeft': '15', 'timeNext': '30'},
{'name': 'Bus 1', 'direction': 'That other place', 'timeLeft': '5', 'timeNext': ''}]
</code></pre>