我正在为"重复"添加不同的值。循环:
repeated=[]
for x in range(0,(length-1)):
for y in range(1,(length)):
if(x == y):
pass
else:
for i in path[0][x]:
for j in path[0][y]:
if set(i) == set(j):
repeated.append((set(i),capacity[x]))
repeated.append((set(j),capacity[y]))
但是,我不确定将它们添加到下面解释的目的更好:
repeated.append((set(i),capacity[x]))
repeated.append([set(i),capacity[x]])
我正在获得以下输出:
OUTPUT:
[({'H', 'B'}, 5), ({'H', 'B'}, 1), ({'C', 'B'}, 5), ({'C', 'B'}, 3), ({'B', 'A'}, 1), ({'B', 'A'}, 5), ({'B', 'A'}, 5), ({'B', 'A'}, 1)]
我想立即检查哪些值相同(在此示例中{' H',' B'}两次相同且{' C&#39 ;,' B'}两次......)并添加其数值以查看哪一个是最大值(添加后)。
对于此示例,{' H',' B'} = 6(5 + 1),{' C',' B&# 39;} = 8(5 + 3)和{' B',' A'} = 12(1 + 5 + 5 + 1),所以我的输出应为12(其中是加起来的3个值的最大值。
我不知道如何访问"重复"为了做到这一点。
非常感谢你!
答案 0 :(得分:4)
您可以使用collections.Counter
对元素进行分组并确定其总数。 Counter
还提供了一些用于获取最常见元素的函数。不过,您必须将set
转换为frozenset
,因此您可以将它们用作词典中的键。
lst = [({'H', 'B'}, 5), ({'H', 'B'}, 1), ({'C', 'B'}, 5), ({'C', 'B'}, 3), ({'B', 'A'}, 1), ({'B', 'A'}, 5), ({'B', 'A'}, 5), ({'B', 'A'}, 1)]
aggregated = collections.Counter()
for x, y in lst:
aggregated[frozenset(x)] += y
print(aggregated)
# Counter({frozenset({'B', 'A'}): 12, frozenset({'B', 'C'}): 8, frozenset({'B', 'H'}): 6})
print(aggregated.most_common(1))
# [(frozenset({'B', 'A'}), 12)]
答案 1 :(得分:1)
以下是您的数据:
open("/home/serj/work/beautytorch/venv/local/lib/python2.7/site-packages/dlib/__init__.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=43, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f7ef51ca000
read(3, "from .dlib import *\n__version__ "..., 4096) = 43
write(2, " ", 4 ) = 4
write(2, "from .dlib import *\n", 20from .dlib import *
) = 20
close(3) = 0
munmap(0x7f7ef51ca000, 4096) = 0
write(2, "ImportError", 11ImportError) = 11
write(2, ": ", 2: ) = 2
write(2, "libboost_python.so.1.64.0: canno"..., 84libboost_python.so.1.64.0: cannot open shared object file: No such file or directory) = 84
write(2, "\n", 1
) = 1
第一项任务是对相应的值求和,如{'H','B'} = 6(5 + 1)。
repeated = [({'H', 'B'}, 5), ({'H', 'B'}, 1), ({'C', 'B'}, 5), ({'C', 'B'}, 3), ({'B', 'A'}, 1), ({'B', 'A'}, 5), ({'B', 'A'}, 5), ({'B', 'A'}, 1)]
现在from collections import defaultdict
c = defaultdict(int)
for (k,v) in repeated:
c[tuple(k)] += v
看起来像这样:
c
你想要{('H', 'B'): 6, ('C', 'B'): 8, ('A', 'B'): 12}
:
max(6,8,12)
答案 2 :(得分:0)
@tobias_k的答案很棒。 但是如果您更喜欢不使用计数器的解决方案,那么您可以看一下:
repeated = [({'H', 'B'}, 5), ({'H', 'B'}, 1), ({'C', 'B'}, 5), ({'C', 'B'}, 3), ({'B', 'A'}, 1), ({'B', 'A'}, 5), ({'B', 'A'}, 5), ({'B', 'A'}, 1)]
d = {}
for a, b in repeated:
if d.get(frozenset(a)):
d[frozenset(a)] = d[frozenset(a)] + b
else:
d[frozenset(a)] = b
print (d)
# {frozenset({'B', 'H'}): 6, frozenset({'B', 'C'}): 8, frozenset({'B', 'A'}): 12}