以下简单代码为我提供了200个元素的长度3的可能组合。
from itertools import combinations
comb = combinations( range(200), 3 )
Run Code Online (Sandbox Code Playgroud)
我想以随机顺序获取组合,以便选择前N个组合。但是,如果我将梳子转换为一个列表并按如下所示对其进行混洗,则可能会出现内存错误,因为该列表可能包含太多元素:
comb = list(comb) # This might be huge and give a memory error
random.shuffle(comb)
N = 10
comb = comb[:10] # get only the first N random combinations
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以获取N个随机组合吗?(即,不是按照itertools.combinations生成的顺序)。
我有两个列表L1和L2.L1中的每个唯一元素是在第二列表L2中具有值的键.我想创建一个字典,其中值是L2中与L1中相同键相关联的元素的总和.
我做了以下但我对这段代码并不感到自豪.有没有更简单的pythonic方法呢?
L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
W = range(len(L)) # as L2
d = { l:[] for l in L }
for l,w in zip(L,W): d[l].append(w)
d = {l:sum(v) for l,v in d.items()}
Run Code Online (Sandbox Code Playgroud)
编辑:
问:我如何知道L2的哪个元素与L1的给定关键元素相关联?
答:如果他们有相同的索引.例如,如果元素7在L1中重复3次(例如L1 [2] == L1 [7] == L1 [8] = 7),那么我希望键7的值为L2 [2] + L2 [7] + L2 [8]