当前位置: 首页>>代码示例>>Python>>正文


Python ChainMap.keys方法代码示例

本文整理汇总了Python中collections.ChainMap.keys方法的典型用法代码示例。如果您正苦于以下问题:Python ChainMap.keys方法的具体用法?Python ChainMap.keys怎么用?Python ChainMap.keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在collections.ChainMap的用法示例。


在下文中一共展示了ChainMap.keys方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: combine_map

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
def combine_map():
    a = {'x': 1, 'z': 3 }
    b = {'y': 2, 'z': 4 }
    c = ChainMap(a,b)
    print(c['x']) # Outputs 1 (from a)
    print(c['y']) # Outputs 2 (from b)
    print(c['z']) # Outputs 3 (from a)

    print(len(c))
    print(list(c.keys()))
    print(list(c.values()))

    c['z'] = 10
    c['w'] = 40
    del c['x']
    print(a)
    # del c['y']

    values = ChainMap()
    values['x'] = 1
    # Add a new mapping
    values = values.new_child()
    values['x'] = 2
    # Add a new mapping
    values = values.new_child()
    values['x'] = 3
    print(values)
    print(values['x'])
    # Discard last mapping
    values = values.parents
    print(values['x'])
    # Discard last mapping
    values = values.parents
    print(values['x'])
    print(values)
开发者ID:Barathrum-Liu,项目名称:python3-cookbook,代码行数:37,代码来源:p20_combine_map.py

示例2: get_raw_results

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
 def get_raw_results(self):
     columns = []
     response_cols = []
     for p, responses in self._stored_responses.items():
         for i, response in responses.items():
             response = ChainMap(
                 response, {'participant_id': p, 'active_item_id': i})
             if not columns:
                 columns.extend(response.keys())
             response_cols.append([response[c] for c in columns])
     return columns, response_cols
开发者ID:foolswood,项目名称:questioneer,代码行数:13,代码来源:in_memory.py

示例3: ScopeStack

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
class ScopeStack(object):
    def __init__(self):
        self.data = ChainMap({})
        self.special_forms = {}

    def __contains__(self, key):
        return key in self.data

    def set(self, key, value, special_form=False):
        if not special_form:
            self.data[key] = value
        else:
            self.special_forms[key] = value

        if not self.validate():
            raise RuntimeError("Special form overwriten")

    def unset(self, key):
        del self.data[key]

    def is_empty(self):
        return len(self.data) == 0

    def new_scope(self):
        self.data = self.data.new_child()

    def drop_scope(self):
        self.data = self.data.parents

    def get_scope_identifiers(self, root=False):
        first_level = self.data.maps[0] if len(self.data.maps) > 0 else {}
        merged_stmts = list(first_level.values())

        if root:
            merged_stmts = list(self.special_forms.values()) + merged_stmts

        return sorted(merged_stmts, key=lambda x: x.value)

    def validate(self):
        normal_scope = set(self.data.keys())
        special_form_scope = set(self.special_forms.keys())
        return len(normal_scope.intersection(special_form_scope)) == 0
开发者ID:jmanuel1,项目名称:cobrascript,代码行数:44,代码来源:utils.py

示例4: ch1_20

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
def ch1_20():
    '''
    1.20 将多个映射合并为单个映射
    使用collections ChainMap解决
    '''

    print("\nch1_20:")

    from collections import ChainMap

    a={'x':1,'z':3}
    b={'y':2,'z':4}

    c = ChainMap(a,b) #使用原始的字典
    print(c['x'],c['y'],c['z'])

    print(list(c.keys()),list(c.values()))

    #用新建字典代替
    merged = dict(b)
    merged.update(a)
    print(merged['x'],merged['y'],merged['z'])
开发者ID:xxg1413,项目名称:python-cookbook,代码行数:24,代码来源:Chapter1.py

示例5: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
from collections import ChainMap

a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}

c = ChainMap(a, b)

print('< x >', c['x'])
print('< y > ', c['y'])
print('< z >: ', c['z'])

print('< Length >', len(c))
print('< Keys >', list(c.keys()))
print('< Values >', list(c.values()))

c['z'] = 10
print('New A', a)
开发者ID:guidiego,项目名称:python-cookbook-examples,代码行数:19,代码来源:problem20.py

示例6: print

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
  Python 3.3 or greater is needed. Python 3.2 does not have ChainMap
"""

"""
Discussion:
-----------

  A Chainmap takes multiple mappings and makes them logically appear
as one. However, the mappings are not literally merged together. Instead,
a ChainMap simply keeps a list of the underlying mappings and redefines common
dictionary operations to scan the list. Most operations will work. For example:
"""

print("\n\nlen(c): ", len(c))
print("\n\nlist(c.keys()): ", list(c.keys()))
print("\n\nlist(c.values()): ", list(c.values()))

"""
  If there are duplicate keys, the values from the first mapping get
used. Thus, the entry c['z'] in the example would always refer to the
value in dictionary a, not the value in dictionary b.

  Operations that mutuate the mapping always affect the first mapping
listed.
"""

"""
  As an alternative to ChainMap, you might consider merging dictionaries
together using the update() method. For example:
"""
开发者ID:crazcalm,项目名称:Python_cookbook_favorites,代码行数:32,代码来源:OnePointTwenty.py

示例7: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
#
# Przykład ilustrujący łączenie słowników w obiekt typu ChainMap

a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }

# (a) Prosty przykład ilustrujący łączenie
from collections import ChainMap
c = ChainMap(a,b)
print(c['x'])      # Zwraca 1  (z a)
print(c['y'])      # Zwraca 2  (z b)
print(c['z'])      # Zwraca 3  (z a)

# Wyświetlanie typowych atrybutów
print('len(c):', len(c))
print('c.keys():', list(c.keys()))
print('c.values():', list(c.values()))

# Modyfikowanie wartości
c['z'] = 10
c['w'] = 40
del c['x']
print("a:", a)


# Tworzenie kilku poziomów odwzorowań (przypomina działanie zasięgu)
values = ChainMap()
values['x'] = 1

# Dodawanie nowego odwzorowania
values = values.new_child()
开发者ID:anpadoma,项目名称:python_receptury3,代码行数:33,代码来源:example.py

示例8: scan

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
class scan():
    def __init__(self,method='mcmc'):
        # self.variable_list={}

        self.scalar_list={}
        self.element_list={}
        self.follower_list={}
        self.dependent_list={}
        # self.matrix_list={}
        # self.free_parameter_list={}

        self.variable_list=ChainMap(
            self.scalar_list,self.element_list,self.follower_list,self.dependent_list
        )
        self.free_parameter_list=ChainMap(
            self.scalar_list,self.element_list
        )

        self.block_list={}

        self.method=method.lower()

        # if self.method=='mcmc':
        #     self.Add=self.AddMcmcScalar
        #     self.AddMatrix=self.AddMcmcMatrix
        #     self.GetNewPoint=self.GetNewPoint_mcmc

    def AddToList(self,par):
        if par.name in self.variable_list.keys():# check duplicates
            Caution("parameter '%s' will be overridden"%name)
            goon=input('contineu? (y/n[n])')
            if not goon in ['y','Y']:
                exit()

        # self.variable_list.update({par.name:par})
        # No longer need after variable_list became ChainMap type

        if type(par) is independent_scalar:
            self.scalar_list.update({par.name:par})
        elif type(par) is independent_element:
            self.element_list.update({par.name:par})
        elif type(par) is follower:
            self.follower_list.update({par.name:par})
        elif type(par) is dependent_scalar:
            self.dependent_list.update({par.name:par})

        if par.block not in self.block_list.keys():
            self.block_list.update({par.block:{}})
        block_i=self.block_list[par.block]
        block_i.update({par.code:par})

    def AddScalar(self,name,block,code
            ,minimum=None,maximum=None,value=None
            ,prior_distribution=None
            ,step_width=None
            ,**args
        ):
        if prior_distribution==None:
            prior_distribution={#defult prior
            'random':'uniform','mcmc':'normal'
            }[self.method]

        scl=independent_scalar(
            name,block,code,minimum,maximum,value=value
            ,strategy=self.method
            ,prior_distribution=prior_distribution
            ,**args)
        self.AddToList(scl)

    def AddElement(self,name,block,code
            ,minimum=None,maximum=None,value=None
            ,prior_distribution=None
            ,step_width=None
            ,**args
        ):
        if prior_distribution==None:
            prior_distribution={#defult prior
            'random':'uniform','mcmc':'normal'
            }[self.method]

        elm=independent_element(
            name,block,code,minimum,maximum
            ,strategy=self.method
            ,prior_distribution=prior_distribution
            ,**args)
        self.AddToList(elm)

    def AddDependent(self,name,block,code,func=None,variables=None,value=None):
        variable_list=[]
        try:# replace parameter names in variables with parameter objects,
            # then collect them into variable_list
            for var in variables:
                if type(var) is str:
                    var=self.variable_list[var]
                variable_list.append(var)
        except KeyError:
            Error('variable %s do not exist'%var)
        except TypeError:
            pass
        dpd=dependent_scalar(name,block,code,func,variable_list,value)
#.........这里部分代码省略.........
开发者ID:vooum,项目名称:ScanCommander,代码行数:103,代码来源:scan.py

示例9: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}

from collections import ChainMap
c = ChainMap(a, b)
print(c['x']) # 1 from a
print(c['y']) # 2 from b
print(c['z']) # 3 from a 

print(len(c)) # 3
print(list(c.keys())) # ['x', 'y', 'z'],不稳定,顺序会随机
print(list(c.values())) # 同上

# 如果存在重复键,第一次出现的映射值会被返回,总是a中对应的值

# 对于字典的更新或删除操作总是影响的是列表中第一个字典a
c['z'] = 10
c['w'] = 40
print(c)
del c['x']
print(c)
#del c['y'] # 会报错

values = ChainMap()
values['x'] = 1
print(values)
values = values.new_child()
values['x'] = 2
values = values.new_child()
values['x'] = 3
print(values) # ChainMap({'x': 3}, {'x': 2}, {'x': 1})
开发者ID:ajioy,项目名称:python-ex,代码行数:33,代码来源:ex21_merge_dicts_chainmap_update.py

示例10: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
a = {'x' : 1, 'z' : 3}
b = {'y' : 2, 'z' : 4}

'''
现在假设你必须在两个字典中执行查找操作 (比如先从 a 中找,如果找不到再在 b
中找)。
'''
from collections import ChainMap
c = ChainMap(a, b)
print(c['x']) # 1
print(c['y']) # 2
print(c['z']) # 3
print(len(c)) # 3

print(list(c.keys())) # ['x', 'z', 'y']
print(list(c.values())) # [2, 1, 3]

'''
如果出现重复键,那么第一次出现的映射值会被返回。因此,例子程序中的 c['z']
总是会返回字典 a 中对应的值,而不是 b 中对应的值。
'''

'''
对于字典的更新或删除操作总是影响的是列表中第一个字典
'''
c['z'] = 10
c['w'] = 40
del c['x']
print(a) # {'w': 40, 'z': 10}
'''
开发者ID:bodii,项目名称:test-code,代码行数:32,代码来源:20.py

示例11: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
# for the existence of keys.

from collections import ChainMap

a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }

c = ChainMap(a,b) # If there are duplicate keys, the values from the first mapping get used.


print (c['x'])
print (c['y'])
print (c['z'])
# a ChainMap simply keeps a list of the underlying mappings and 
# redefines common dictionary operations to scan the list
print (c, list(c.keys()), list(c.values()), len(c))

# Operations that mutate the mapping always affect the first mapping listed
c['z'] = 10
c['w'] = 40
print (c, a)

a['w'] = 30
print (c, a)

# KeyError: "Key not found in the first mapping: 'y'"
# del c['y']

# ------------------------------------------------------------------------

values = ChainMap()
开发者ID:fluency03,项目名称:Python-Cookbook,代码行数:33,代码来源:1.20.multi_to_single_mapping.py

示例12: knowledge

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
class knowledge(object):
    """ george is a good little monkey, but always curious"""

    gibberish = 'Hoo! Hoo! Ha! Ha!'
    mlue = "the meaning of Life, the Universe, and Everything"
    the_ultimate_question = "the Ultimate Question"
    defaults = {the_ultimate_question: None}
    the_ultimate_answer = 42
    uq = defaultdict(lambda: knowledge.ua)

    who = {"Who is Mommy": "Mother"}
    what = {"What is the Man in the Yellow Hat": "Man"
           ,"What is Person": "kindof Animal"
           ,"What is Animal": "kindof Living Thing"
           ,"What is Man": "kindof Person"
           ,"What is Man": "Male Person"
           ,"What is Hat": "kindof Covering"
           ,"What is Hat": "Covering for Head"
           ,"What Hat is madeof": "Straw"
           ,"What is Straw": "partof kindof Plant"
           ,"What is Plant": "kindof Living Thing"
           ,"What is Head": "partof Person"
           ,"What is Yellow": "kindof Color"
           ,"What is Color": "propertyof Thing"
           ,"What Color is Straw": "Yellow"
           ,"What is Woman": "kindof Person"
           ,"What is Woman": "Female Person"
           ,"What is Child": "kindof Person"
           ,"What is Child": "Young Person"
           ,"What is Baby": "New Person"
           ,"What is Fetus": "Baby in Mother"
           ,"What is Mother": "Woman having Baby"
           }
    where = {"Where is Mommy": "School"
            ,"Are we there, yet": "No"
            ,"Are we there, yet": "Almost" # where answers can change 
            }
    when = {"When will Mommy be Home": "Dinner Time"
           ,"When is Dinner Time": "6:30 PM"
           ,"Is it Dinner Time, yet": "No"
           ,"Is it Dinner Time, yet": "No"
           ,"Is it Dinner Time, yet": "Almost" # when answers can change 
           }
    why = {"Why": "Because"} # why answers can probably change, too

    def __init__(self):
        """ mock knowledge base, use triple store ? """ 
        self.base = ChainMap(self.who
                            ,self.what
                            ,self.where
                            ,self.when
                            ,self.why
                            ,self.defaults
                            ,self.uq
                            )

    def __iter__(self):
        return(self)

    def __next__(self):
        return self.next()

    def next(self):
        while True:
            try:
                for q in self.base.keys():
                    if not(self.the_ultimate_answer == self.base[q]):
                        yield q
            finally:
                raise StopIterator
        # print("base = {}".format(self.base))

    def close(self):
        # persist knowledge base
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc, value, tb):
        self.close()

    def ask(self,question):
        #return input("{} ".format(question))
        if self.gibberish == question:
            return None
        response = self.base[question.rstrip('?')]
        if response and self.the_ultimate_answer != response:
            return response
        # return easy_input(question+"?",[False,True])
        response = randint(0,2)
        # finite improbability drive
        if response < 2:
            if bool(response):
                return 'Yes'
            else:
                return 'No'
        else:
            return 'Dunno'

#.........这里部分代码省略.........
开发者ID:smattin,项目名称:george,代码行数:103,代码来源:kb.py

示例13: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}

from collections import ChainMap
c = ChainMap(a, b)

print(c['x'])
print(c['y'])
print(c['z'])
print(c)
print(len(c))
print(c.keys())
print(c.values())

//output
1
2
3
ChainMap({'z': 3, 'x': 1}, {'z': 4, 'y': 2})
3
KeysView(ChainMap({'z': 3, 'x': 1}, {'z': 4, 'y': 2}))
ValuesView(ChainMap({'z': 3, 'x': 1}, {'z': 4, 'y': 2}))

c['z'] = 10
c['w'] = 40

In [28]: c
Out[28]: ChainMap({'z': 10, 'x': 1, 'w': 40}, {'z': 4, 'y': 2})
In [29]: del c['x']
In [30]: a
Out[30]: {'w': 40, 'z': 10}
开发者ID:dataAlgorithms,项目名称:data,代码行数:33,代码来源:dsAlgo_combineMultiMapToSingleMap.py

示例14: default

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
def default():
    c = ChainMap(a, b)
    print(len(c), list(c.keys()), list(c.values()))
    print(c['x'], c['y'], c['z'])
开发者ID:Chiva-Zhao,项目名称:pproject,代码行数:6,代码来源:combindict.py

示例15: ChainMap

# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import keys [as 别名]
# -*- coding: utf-8 -*-
# @Author: joshua
# @Date:   2015-05-23 20:06:31
# @Last Modified by:   Joshua Liu
# @Last Modified time: 2015-05-24 19:24:22

from collections import ChainMap

a = {'x': 1, 'z': 3}
b = {'y': 1, 'z': 4}
c = ChainMap(a, b)
print(c)

# 事实上ChainMap并没有真正把多个映射合成一个,而是通过逻辑重新定义了映射的常用操作
print(len(c))
print(list(c.keys()))
print(list(c.values()))

# 如果有重复的键值,将从第一个映射取值,所以c['z'] == a['z'],而不是等于b['z']
# 对合成映射c的操作只影响第一个映射a

c['z'] = 10
c['w'] = 40
del c['x']
print(a)

try:
    # 因为
    del c['y']
except Exception as e:
    print(e)
开发者ID:fooyou,项目名称:Exercise,代码行数:33,代码来源:20_Combine_maps.py


注:本文中的collections.ChainMap.keys方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。