我有一个元组列表,我需要拆分,元组中的每个第二个元素都大于1,进入一个"元组列表列表#34;。从这些元组列表中,我试图计算新列表中第一个元组的第一个元素与新列表中最后一个元组的第一个元素之间的差异。对不起,如果这看起来很混乱。
以下面的例子为例:
zp = [(1.31, 0), (1.32, 0),
(1.33, 0), (1.34, 0),
(1.35, 1), (1.36, 2),
(1.37, 3), (1.37, 4),
(1.39, 5), (1.38, 6),
(1.40, 7), (1.41, 8),
(1.42, 9), (1.43, 10),
(1.44, 0), (1.45, 0),
(1.46, 0), (1.47, 0),
(1.48, 1), (1.49, 2),
(1.50, 3), (1.51, 4),
(1.52, 0), (1.53, 0),
(1.54, 1), (1.55, 2),
(1.56, 3), (1.57, 4),
(1.48, 0), (1.59, 0),
(1.60, 0), (1.61, 0),
(1.62, 1), (1.63, 2),
(1.64, 3), (1.65, 4),
(1.66, 0), (1.67, 0),
(1.68, 1), (1.69, 2),
(1.70, 3), (1.71, 4)]
从这里我列举了元组的第二个元素是>的所有位置。 1,获取zp
的索引序列:
enums = [j for j, k in enumerate(zp) if not k[1] in (0,1)]
enums
[5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 20, 21, 25, 26, 27, 33, 34, 35, 39, 40, 41]
在这里,我开始怀疑我正在走错路,因为我已经在很多圈子中走了一圈。例如,使用for循环来获取zp
的切片:
for k in range(1, len(enums)):
if enums[k] - enums[k-1] > 1:
print "index k-1", k-1, "end if seq: emum[k-1]", enums[k-1], " --", "index k", k, "start if next seq: emum[k-1]", enums[k]
然后从那里切换zp
并更改enum
索引...所以必须有更好的方法吗?
欢迎任何建议。
*编辑
预期结果:
[(1.36, 2),(1.37, 3), (1.37, 4),(1.39, 5), (1.38, 6),(1.40, 7), (1.41, 8),(1.42, 9), (1.43, 10)],
[(1.49, 2),(1.50, 3), (1.51, 4)],
[(1.55, 2),(1.56, 3), (1.57, 4)],
[(1.63, 2),(1.64, 3), (1.65, 4)],
[(1.69, 2),(1.70, 3), (1.71, 4)]]
答案 0 :(得分:1)
您可以使用itertools.groupby
根据每个元组的第二项>的条件对结果进行分组。 1(lambda x: x[1] > 1
)。这将为每个条件具有相同结果的连续项返回一个组(True
或False
)。然后,我们可以使用列表推导来忽略由于条件为False
而分组的组,并将组转换为条件为True
的列表。
import itertools
A = [list(group) for val, group in itertools.groupby(zp, lambda x: x[1] > 1) if val]
# [[(1.36, 2), (1.37, 3), (1.37, 4), (1.39, 5), (1.38, 6), (1.4, 7), (1.41, 8), (1.42, 9), (1.43, 10)],
# [(1.49, 2), (1.5, 3), (1.51, 4)],
# [(1.55, 2), (1.56, 3), (1.57, 4)],
# [(1.63, 2), (1.64, 3), (1.65, 4)],
# [(1.69, 2), (1.7, 3), (1.71, 4)]]