當前位置: 首頁>>代碼示例>>Python>>正文


Python builtins.filter方法代碼示例

本文整理匯總了Python中builtins.filter方法的典型用法代碼示例。如果您正苦於以下問題:Python builtins.filter方法的具體用法?Python builtins.filter怎麽用?Python builtins.filter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在builtins的用法示例。


在下文中一共展示了builtins.filter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: oldfilter

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def oldfilter(*args):
        """
        filter(function or None, sequence) -> list, tuple, or string

        Return those items of sequence for which function(item) is true.
        If function is None, return the items that are true.  If sequence
        is a tuple or string, return the same type, else return a list.
        """
        mytype = type(args[1])
        if isinstance(args[1], basestring):
            return mytype().join(builtins.filter(*args))
        elif isinstance(args[1], (tuple, list)):
            return mytype(builtins.filter(*args))
        else:
            # Fall back to list. Is this the right thing to do?
            return list(builtins.filter(*args))

    # This is surprisingly difficult to get right. For example, the
    # solutions here fail with the test cases in the docstring below:
    # http://stackoverflow.com/questions/8072755/ 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:22,代碼來源:noniterators.py

示例2: _init_commands

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def _init_commands(self):
        command_re = re.compile("^(do_(.*))$")
        commands = [command_re.match(v).groups() for v in list(filter(command_re.search, dir(self)))]

        self.commands = PrefixDict()

        for command in commands:
            self.commands.add(command[1], getattr(self, command[0]))

        for command, controller in list(self.controller_map.items()):
            try:
                controller = controller()
            except Exception:
                pass

            self.commands.add(command, controller) 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:18,代碼來源:controllerlib.py

示例3: __and__

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def __and__(self, other):
        """Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        """
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in filter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:20,代碼來源:__init__.py

示例4: oldfilter

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def oldfilter(*args):
        """
        filter(function or None, sequence) -> list, tuple, or string
        
        Return those items of sequence for which function(item) is true.
        If function is None, return the items that are true.  If sequence
        is a tuple or string, return the same type, else return a list.
        """
        mytype = type(args[1])
        if isinstance(args[1], basestring):
            return mytype().join(builtins.filter(*args))
        elif isinstance(args[1], (tuple, list)):
            return mytype(builtins.filter(*args))
        else:
            # Fall back to list. Is this the right thing to do?
            return list(builtins.filter(*args))

    # This is surprisingly difficult to get right. For example, the
    # solutions here fail with the test cases in the docstring below:
    # http://stackoverflow.com/questions/8072755/ 
開發者ID:QData,項目名稱:deepWordBug,代碼行數:22,代碼來源:noniterators.py

示例5: __and__

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in filter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result 
開發者ID:hughperkins,項目名稱:kgsgo-dataset-preprocessor,代碼行數:20,代碼來源:pandas_py3k.py

示例6: anchor_id

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def anchor_id(self):
        """ Yields the anchor tag as parsed from the original token.
            Chunks that are anchors have a tag with an "A" prefix (e.g., "A1").
            Chunks that are PNP attachmens (or chunks inside a PNP) have "P" (e.g., "P1").
            Chunks inside a PNP can be both anchor and attachment (e.g., "P1-A2"),
            as in: "clawed/A1 at/P1 mice/P1-A2 in/P2 the/P2 wall/P2"
        """
        id = ""
        f = lambda ch: list(filter(lambda k: self.sentence._anchors[k] == ch, self.sentence._anchors))
        if self.pnp and self.pnp.anchor:
            id += "-" + "-".join(f(self.pnp))
        if self.anchor:
            id += "-" + "-".join(f(self))
        if self.attachments:
            id += "-" + "-".join(f(self))
        return id.strip("-") or None 
開發者ID:kakaobrain,項目名稱:helo_word,代碼行數:18,代碼來源:tree.py

示例7: lfilter

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def lfilter(*args, **kwargs):
        return list(filter(*args, **kwargs)) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:4,代碼來源:__init__.py

示例8: num_cores

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def num_cores(self):
        """The number of virtual cores of this VM."""
        valid_vmcss = list(filter(self.is_valid_vmcs, self.vmcss))
        # Count only unique VPIDs if the hypervisor uses them.
        uniq_vpids = set([v.VPID for v in valid_vmcss])
        if len(uniq_vpids) != 1:
            return len(uniq_vpids)
        else:
            return len(valid_vmcss) 
開發者ID:google,項目名稱:rekall,代碼行數:11,代碼來源:hypervisors.py

示例9: show_distribution

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def show_distribution(title, histogram, unit, hist, cluster, like=None, timestamp="", **ignore):
        prefixes = cluster.get_node_names()

        likes = compile_likes(like)

        columns = ["%s%%" % (n) for n in range(10, 110, 10)]
        percentages = columns[:]
        columns.insert(0, 'node')

        title_suffix = CliView._get_timestamp_suffix(timestamp)
        description = "Percentage of records having %s less than or " % (hist) + \
                      "equal to value measured in %s" % (unit)

        namespaces = set(filter(likes.search, list(histogram.keys())))

        for namespace, node_data in list(histogram.items()):
            if namespace not in namespaces or not node_data or isinstance(node_data, Exception):
                continue

            t = Table("%s - %s in %s%s" % (namespace, title, unit,
                                           title_suffix), columns, description=description)
            for node_id, data in list(node_data.items()):
                if not data or isinstance(data, Exception):
                    continue

                percentiles = data['percentiles']
                row = {}
                row['node'] = prefixes[node_id]
                for percent in percentages:
                    row[percent] = percentiles.pop(0)

                t.insert_row(row)

            CliView.print_result(t) 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:36,代碼來源:view.py

示例10: show_object_distribution

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def show_object_distribution(title, histogram, unit, hist, bucket_count, set_bucket_count, cluster, like=None, timestamp="", loganalyser_mode=False, **ignore):
        prefixes = cluster.get_node_names()

        likes = compile_likes(like)

        title_suffix = CliView._get_timestamp_suffix(timestamp)
        description = "Number of records having %s in the range " % (hist) + \
                      "measured in %s" % (unit)

        namespaces = set(filter(likes.search, list(histogram.keys())))

        for namespace, node_data in list(histogram.items()):
            if namespace not in namespaces:
                continue
            columns = []
            for column in node_data["columns"]:
                # Tuple is required to give specific column display name,
                # otherwise it will print same column name but in title_format
                # (ex. KB -> Kb)
                columns.append((column, column))
            columns.insert(0, 'node')
            t = Table("%s - %s in %s%s" % (namespace, title, unit,
                                           title_suffix), columns, description=description)
            if not loganalyser_mode:
                for column in columns:
                    if column != 'node':
                        t.add_data_source(
                            column, Extractors.sif_extractor(column))

            for node_id, data in list(node_data.items()):
                if node_id == "columns":
                    continue

                row = data['values']
                row['node'] = prefixes[node_id]
                t.insert_row(row)

            CliView.print_result(t)
            if set_bucket_count and (len(columns) - 1) < bucket_count:
                print("%sShowing only %s bucket%s as remaining buckets have zero objects%s\n" % (terminal.fg_green(), (len(columns) - 1), "s" if (len(columns) - 1) > 1 else "", terminal.fg_clear())) 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:42,代碼來源:view.py

示例11: show_mapping

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def show_mapping(col1, col2, mapping, like=None, timestamp="", **ignore):
        if not mapping:
            return

        column_names = []
        column_names.insert(0, col2)
        column_names.insert(0, col1)

        title_suffix = CliView._get_timestamp_suffix(timestamp)
        t = Table("%s to %s Mapping%s" % (col1, col2, title_suffix), column_names,
                  title_format=TitleFormats.no_change, style=Styles.HORIZONTAL)

        if like:
            likes = compile_likes(like)
            filtered_keys = list(filter(likes.search, list(mapping.keys())))

        else:
            filtered_keys = list(mapping.keys())

        for col1_val, col2_val in list(mapping.items()):
            if col1_val not in filtered_keys:
                continue
            row = {}
            if not isinstance(col2_val, Exception):
                row[col1] = col1_val
                row[col2] = col2_val
            t.insert_row(row)
        CliView.print_result(t) 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:30,代碼來源:view.py

示例12: asinfo

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def asinfo(results, line_sep, show_node_name, cluster, **kwargs):
        like = set([])
        if 'like' in kwargs:
            like = set(kwargs['like'])

        for node_id, value in list(results.items()):

            if show_node_name:
                prefix = cluster.get_node_names()[node_id]
                node = cluster.get_node(node_id)[0]
                print("%s%s (%s) returned%s:" % (terminal.bold(), prefix, node.ip, terminal.reset()))

            if isinstance(value, Exception):
                print("%s%s%s" % (terminal.fg_red(), value, terminal.reset()))
                print("\n")
            else:
                if is_str(value):
                    delimiter = find_delimiter_in(value)
                    value = value.split(delimiter)

                    if like:
                        likes = compile_likes(like)
                        value = list(filter(likes.search, value))

                    if line_sep:
                        value = "\n".join(value)
                    else:
                        value = delimiter.join(value)

                    print(value)
                    if show_node_name:
                        print()
                else:
                    i = 1
                    for name, val in list(value.items()):
                        print(i, ": ", name)
                        print("    ", val)
                        i += 1
                    if show_node_name:
                        print() 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:42,代碼來源:view.py

示例13: _matchImageFilter

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def _matchImageFilter(self, imagelist, gamenameFromFile):
        
        mediaPath = 'testdata\artwork\SNES\%GAME%.*'
        pathnameFromFile = mediaPath.replace("%GAME%", gamenameFromFile)
        pathToSearch = re.escape(os.path.normpath(pathnameFromFile.replace('.*', '')))
        foundImage = ''
        
        timestamp1 = time.clock()
        pattern = re.compile('%s\..*$' %pathToSearch)
        foundImage = list(filter(pattern.match, imagelist))
        timestamp2 = time.clock()
        diff = (timestamp2 - timestamp1) * 1000
        print ('filter took %s ms' %diff)
                
        return foundImage[0] 
開發者ID:maloep,項目名稱:romcollectionbrowser,代碼行數:17,代碼來源:test_imageloading.py

示例14: identify_scanned_page

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def identify_scanned_page(self, boxes, page_bbox, page_width, page_height):
        plane = Plane(page_bbox)
        plane.extend(boxes)
        cid2obj = [set([i]) for i in range(len(boxes))]  # initialize clusters
        # default object map to cluster with its own index
        obj2cid = list(range(len(boxes)))
        prev_clusters = obj2cid
        while True:
            for i1, b1 in enumerate(boxes):
                for i2, b2 in enumerate(boxes):
                    box1 = b1.bbox
                    box2 = b2.bbox
                    if (
                        box1[0] == box2[0]
                        and box1[2] == box2[2]
                        and round(box1[3]) == round(box2[1])
                    ):
                        min_i = min(i1, i2)
                        max_i = max(i1, i2)
                        cid1 = obj2cid[min_i]
                        cid2 = obj2cid[max_i]
                        for obj_iter in cid2obj[cid2]:
                            cid2obj[cid1].add(obj_iter)
                            obj2cid[obj_iter] = cid1
                        cid2obj[cid2] = set()
            if prev_clusters == obj2cid:
                break
            prev_clusters = obj2cid
        clusters = [[boxes[i] for i in cluster] for cluster in filter(bool, cid2obj)]
        if (
            len(clusters) == 1
            and clusters[0][0].bbox[0] < -0.0
            and clusters[0][0].bbox[1] <= 0
            and abs(clusters[0][0].bbox[2] - page_width) <= 5
            and abs(clusters[0][0].bbox[3] - page_height) <= 5
        ):
            return True
        return False 
開發者ID:HazyResearch,項目名稱:pdftotree,代碼行數:40,代碼來源:TableExtractML.py

示例15: gen_conv_testcase

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import filter [as 別名]
def gen_conv_testcase():
    """
    Generate convolution test cases

    Returns:
        Iterator of (C, D, H, W, N, T, R, S, K, strides, padding)
    """

    def args_filter(args):
        """
        Filter currently not supported case (only symmetric padding allowed).

        Returns:
            True if args shall be kept.
        """
        C, D, H, W, N, T, R, S, K, strides, padding = args
        pad_t, pad_b, pad_l, pad_r = common_conv2d_pool_padding((N, H, W, C),
                                                                (R, S, C, K),
                                                                strides, padding)
        return pad_t == pad_b and pad_l == pad_r

    # test params
    Cs = [2, ]
    Ds = [1, ]
    Hs = [28, 11]
    Ws = [28, 11]
    Ns = [8, ]
    Ts = [1, ]
    Rs = [1, 3]
    Ss = [1, 3]
    Ks = [4, ]
    strides_list = [[1, 1, 1, 1], [1, 2, 3, 1]]
    paddings = ['SAME', 'VALID']
    all_args = list(
        itertools.product(Cs, Ds, Hs, Ws, Ns, Ts, Rs, Ss, Ks, strides_list,
                          paddings))
    return filter(args_filter, all_args) 
開發者ID:NervanaSystems,項目名稱:ngraph-python,代碼行數:39,代碼來源:test_ops_nn.py


注:本文中的builtins.filter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。