小编eLe*_*ner的帖子

改组组合而不将可迭代(itertools.combinations)转换为列表

以下简单代码为我提供了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生成的顺序)。

python combinations shuffle python-itertools

5
推荐指数
1
解决办法
2117
查看次数

创建字典,其中键来自列表,值是另一个列表中相应元素的总和

我有两个列表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]

python dictionary list

2
推荐指数
1
解决办法
343
查看次数

如何打印参数化SQL查询?

一旦插入参数,如何获取带参数化SQL查询的String?

.net c# sql oledb

1
推荐指数
1
解决办法
135
查看次数

标签 统计

python ×2

.net ×1

c# ×1

combinations ×1

dictionary ×1

list ×1

oledb ×1

python-itertools ×1

shuffle ×1

sql ×1