让我们说我的目标数是60.我有一个元素列表,我想找到一对数字,当减去时,其余数小于或等于60(绝对值是可以的) 。当我找到这些数字时,我想将它们添加到一个新的列表中,而没有任何重复。
这是我的代码,但这提供了大量重复。
new_days
的内容为:[353, 34, 172, 218, 356, 37, 83, 175, 267, 177, 269, 361, 88, 134, 180, 226, 272, 318, 364, 45]
i, j = 0, 1
pairs = []
for i in range(len(new_days)):
for j in range(len(new_days)):
val = new_days[j] - new_days[i]
val = abs(val)
if val <= 60:
pair = str(new_days[i]) + ' ' + str(new_days[j])
pairs.append(pair)
我希望保持代码尽可能简单和干净,以便我的老板和同事都知道一点Python可以理解一旦我完成它,如果需要进行任何更改。
答案 0 :(得分:2)
为了按照给定标准过滤所有对,您可以将itertools.combinations
与列表理解表达式一起使用:
>>> from itertools import combinations
>>> my_list = [353, 34, 172, 218, 356, 37, 83, 175, 267, 177, 269, 361, 88, 134, 180, 226, 272, 318, 364, 45]
# filter criterion v
>>> [(i,j) for i, j in combinations(my_list, 2) if abs(i-j)<=60]
[(353, 356), (353, 361), (353, 318), (353, 364), (34, 37), (34, 83), (34, 88), (34, 45), (172, 218), (172, 175), (172, 177), (172, 134), (172, 180), (172, 226), (218, 175), (218, 267), (218, 177), (218, 269), (218, 180), (218, 226), (218, 272), (356, 361), (356, 318), (356, 364), (37, 83), (37, 88), (37, 45), (83, 88), (83, 134), (83, 45), (175, 177), (175, 134), (175, 180), (175, 226), (267, 269), (267, 226), (267, 272), (267, 318), (177, 134), (177, 180), (177, 226), (269, 226), (269, 272), (269, 318), (361, 318), (361, 364), (88, 134), (88, 45), (134, 180), (180, 226), (226, 272), (272, 318), (318, 364)]
但是,如果您想过滤仅连续数字对,您可以将zip
与列表理解表达式一起使用:
# filter content on absolute value of consecutive number v
>>> [(i, j) for i, j in zip(my_list, my_list[1:]) if abs(i-j)<=60]
[(172, 218), (37, 83), (88, 134), (134, 180), (180, 226), (226, 272), (272, 318), (318, 364)]
答案 1 :(得分:0)
此代码段将遍历所有对(不按其他顺序重复):
for i, e1 in enumerate(data):
for e2 in data[i+1:]:
if abs(e1 - e2) <= 60:
print(e1, e2)