问题描述:
wells = [
[
[0, 4, 'earth'],
[4, 8, 'suglinok'],
[8, 20, 'gravel'],
],
[
[0, 4, 'earth'],
[4, 8, 'suglinok'],
[8, 20, 'sand'],
],
[
[0, 4, 'earth'],
[4, 16, 'suglinok'],
[16, 24, 'gravel'],
]
]
points_by_description = {}
for well in wells:
for point in well:
start, end, description = point
if description in points_by_description:
points_by_description[description].extend([start, end])
else:
points_by_description[description] = [start, end]
for description, points in points_by_description.items():
for i in range(0, len(points), 2):
print([points[i], points[i + 1]], end=" ")
print()
My script connects the beginnings and ends of lists with the same descriptions.
Output looks like this:
[0, 4] [0, 4] [0, 4]
[4, 8] [4, 8] [4, 16]
[8, 20] [16, 24]
[8, 20]
I need to change the code so that connections are only looked for in adjacent lists.
The output should look like this:
[0, 4] [0, 4] [0, 4]
[4, 8] [4, 8] [4, 16]
[8, 20]
[8, 20]
[16, 24]
no idea how to do this
解决方案 1[最佳方案][1]
Keep track if you have seen the description in a well
from collections import defaultdict
points_by_description = defaultdict(list)
descriptionInWell = defaultdict(set)
for wellIdx,well in enumerate(wells):
for start, end, description in well:
descriptionInWell[description].add(wellIdx)
if not(wellIdx-1 in descriptionInWell[description]):
points_by_description[description].append([])
points_by_description[description][-1].extend([start, end])
for description, pointLists in points_by_description.items():
for points in pointLists:
for i in range(0, len(points), 2):
print([points[i], points[i + 1]], end=" ")
print()
解决方案 2:[2]
The exact expected output is unclear, but assuming you want a dictionary with the description as key and a list of list as value with the consecutive values with the same description grouped in a sublist, you could use zip
, itertools.chain
, itertools.groupby
:
from itertools import groupby, chain
out = {}
for k, g in groupby(chain.from_iterable(zip(*wells)), key=lambda x: x[-1]):
out.setdefault(k, []).append([x for l in g for x in l[:-1]])
Output:
{'earth': [[0, 4, 0, 4, 0, 4]],
'suglinok': [[4, 8, 4, 8, 4, 16]],
'gravel': [[8, 20], [16, 24]],
'sand': [[8, 20]]}
参考链接:
Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.
Article Source: StackOverflow
[1] rioV8
[2] mozway