我有一个与每一个指南针方位从1到360度相关的距离列表,也存储为一个列表。我想压缩列表,以便给出与距离相关的方位范围。
发自:
bearings = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
distance = [5, 10, 15, 15, 15, 20, 20, 10, 10, 5]至:
bearings = [1, 2, 3-5, 6-7, 8-9, 10]
distance = [5, 10, 15, 20, 10, 5]有什么办法来解决这个问题吗?提前感谢!
发布于 2021-12-27 03:36:35
通过通过重复值“集群”距离数组,我们可以重新创建轴承阵列。
也许有一种更像python的方法可以做到这一点,但这是一个开始的地方!
bearings = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
distance = [5, 10, 15, 15, 15, 20, 20, 10, 10, 5]
clumps = []
current_clump = []
# Clump repeating distances together
last_val = None
for i in range(len(distance)):
current_val = distance[i]
# if this element (distance) is the same as the last, add it to the current clump
# otherwise add the current clump to our clumps list and create a new empty one
if current_val == last_val or last_val is None:
current_clump.append(current_val)
else:
clumps.append(current_clump)
current_clump = [current_val]
last_val = current_val
# Add the 'leftover' clump after the loop is done
clumps.append(current_clump)
# Create the output "ranged_indices" array that will have our desired ranged values
ranged_indices = []
current_indice = 0;
for i in range(len(clumps)):
current_len = len(clumps[i])
if current_len == 1:
ranged_indices.append(current_indice+1)
else:
high_end = (current_indice+current_len)
ranged_indices.append(str(current_indice+1)+'-'+str(high_end))
current_indice += current_len
print(ranged_indices)
print(clumps)发布于 2021-12-27 03:58:33
只是为了好玩,我试着用itertools.groupby在一行中这样做。如果您正在编写数据处理或其他方面的丢弃代码,这就可以了。否则,我建议将它分解为一个for循环,这样它就更易于维护了。
from itertools import groupby
bearings = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
distance = [5, 10, 15, 15, 15, 20, 20, 10, 10, 5]
new_bearings, new_distance = zip(
*[
(f"{pairs[0][0]}-{pairs[-1][0]}", k)
if len(pairs) > 1
else (str(pairs[0][0]), pairs[0][1])
for k, pairs in [
(k, list(g))
for k, g in groupby(zip(bearings, distance), key=lambda x: x[1])
]
]
)
print(f"{new_bearings=}")
# new_bearings=('1', '2', '3-5', '6-7', '8-9', '10')
print(f"{new_distance=}")
# new_distance=(5, 10, 15, 20, 10, 5)我讨厌它-)
其思想是,内部循环是按距离分组,并在它们相同的地方给出元组。您需要返回(k, list(g)),因为g是一个迭代器,您需要一个用于len和切片的列表。
一旦您有了元组列表,丑陋的字符串操作就是给出您的lower-upper表示法,或者只是将第一个元素转换成一个字符串(如果只有一个对)。
https://stackoverflow.com/questions/70491350
复制相似问题