16

我经常想在 python 中存储一个无序的集合。itertools.groubpy做正确的事情,但几乎总是需要先对项目进行按摩,然后在迭代器被消耗之前捕获它们。

是否有任何快速的方法来获得这种行为,无论是通过标准的 python 模块还是简单的 python 成语?

>>> bucket('thequickbrownfoxjumpsoverthelazydog', lambda x: x in 'aeiou')
{False: ['t', 'h', 'q', 'c', 'k', 'b', 'r', 'w', 'n', 'f', 'x', 'j', 'm', 'p',
    's', 'v', 'r', 't', 'h', 'l', 'z', 'y', 'd', 'g'],
 True: ['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'a', 'o']}
>>> bucket(xrange(21), lambda x: x % 10)
{0: [0, 10, 20],
 1: [1, 11],
 2: [2, 12],
 3: [3, 13],
 4: [4, 14],
 5: [5, 15],
 6: [6, 16],
 7: [7, 17],
 8: [8, 18],
 9: [9, 19]}
4

5 回答 5

22

This has come up several times before -- (1), (2), (3) -- and there's a partition recipe in the itertools recipes, but to my knowledge there's nothing in the standard library.. although I was surprised a few weeks ago by accumulate, so who knows what's lurking there these days? :^)

When I need this behaviour, I use

from collections import defaultdict

def partition(seq, key):
    d = defaultdict(list)
    for x in seq:
        d[key(x)].append(x)
    return d

and get on with my day.

于 2012-10-04T04:44:07.503 回答
5

这是一个简单的两个班轮

d = {}
for x in "thequickbrownfoxjumpsoverthelazydog": d.setdefault(x in 'aeiou', []).append(x)

编辑:

只需添加您的其他案例以确保完整性。

d={}
for x in xrange(21): d.setdefault(x%10, []).append(x)
于 2012-10-04T04:33:46.030 回答
2

当谓词是布尔值时,这是上面的变体partition(),避免了dict/的成本defaultdict

def boolpartition(seq, pred):
    passing, failing = [], []
    for item in seq:
        (passing if pred(item) else failing).append(item)
    return passing, failing

示例用法:

>>> even, odd = boolpartition([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
>>> even
[2, 4]
>>> odd
[1, 3, 5]
于 2015-01-26T12:16:35.453 回答
2

如果它pandas.DataFrame以下也有效,则利用pd.cut()

from sklearn import datasets
import pandas as pd

# import some data to play with
iris = datasets.load_iris()
df_data = pd.DataFrame(iris.data[:,0])  # we'll just take the first feature

# bucketize
n_bins = 5
feature_name = iris.feature_names[0].replace(" ", "_")
my_labels = [str(feature_name) + "_" + str(num) for num in range(0,n_bins)]
pd.cut(df_data[0], bins=n_bins, labels=my_labels)

屈服

0      0_1
1      0_0
2      0_0
[...]

如果您不设置labels,输出将是这样的

0       (5.02, 5.74]
1      (4.296, 5.02]
2      (4.296, 5.02]
[...]
于 2017-10-30T02:53:39.197 回答
-1

Edit:

Using DSM's answer as a start, here is a slightly more concise, general answer:

d = defaultdict(list)
map(lambda x: d[x in 'aeiou'].append(x),'thequickbrownfoxjumpsoverthelazydog')

or

d = defaultdict(list)
map(lambda x: d[x %10].append(x),xrange(21))
#

Here is a two liner:

d = {False:[],True:[]}
filter(lambda x: d[True].append(x) if x in 'aeiou' else d[False].append(x),"thequickbrownfoxjumpedoverthelazydogs")

Which can of course be made a one-liner:

d = {False:[],True:[]};filter(lambda x: d[True].append(x) if x in 'aeiou' else d[False].append(x),"thequickbrownfoxjumpedoverthelazydogs")
于 2012-10-04T04:44:45.707 回答