用Python替换列表中的项目

sed*_*deh 1 python dictionary list nested-loops python-3.x

我是python和编程的新手,需要一些帮助替换列表字典中的项目.我想,以取代None'None'下面的词典:

dict = {'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', None],
        'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', None],
        'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', None],
        'Rochester101': [None, None, None, '08/18/2012']}
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

new_dict = {}

for i in dict: #This accesses each dictionary key.
    temp = []
    for j in dict[i]: #This iterates through the inner lists
        if j is None:
            temp.append('None')
        else:
            temp.append(j)
        temp2 = {str(i):temp}
        new_dict.update(temp2)

    print(new_dict)
Run Code Online (Sandbox Code Playgroud)

产量

{'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', 'None'], 
'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', 'None'], 
'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', 'None'], 
'Rochester101': ['None', 'None', 'None', '08/18/2012']}
Run Code Online (Sandbox Code Playgroud)

有没有办法在更少的代码行中使用列表理解或其他方法更有效地执行此操作?应该避免嵌套for循环(因为我在我的代码中有它)?谢谢.

使用Python 3.4.1

daw*_*awg 5

使用字典理解:

>>> {k:[e if e is not None else 'None' for e in v] for k,v in di.items()}
{'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', 'None'], 'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', 'None'], 'Rochester101': ['None', 'None', 'None', '08/18/2012'], 'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', 'None']}
Run Code Online (Sandbox Code Playgroud)

并且不要命名dict,dict因为它将通过该名称掩盖内置函数.


如果您有大量的词典或列表,则可能需要修改数据.如果是这样,这可能是最有效的:

for key, value in di.items():
    for i, e in enumerate(value):
        if e is None: di[key][i]='None'    
Run Code Online (Sandbox Code Playgroud)