在嵌套列表中的元组内大写字符串

时间:2017-12-13 04:52:47

标签: python

我有这样一个嵌套列表,

Keywords_33=[('file', ['with', 'as']),
             ('module', ['from', 'import']),
             ('constant_3', {'bool': ['False', 'True'], 'none': ['None']}),
             ('operator_4',
                      {'boolean_operation': {'and', 'not', 'or'},
                       'comparison': {'is'}}),
             ('sequnce_operation_2', ['in', 'del']),
             ('klass_1', ['class']),
             ('function_7',
                      ['lambda','def','pass',
                       'global','nonlocal',
                       'return','yield']),
             ('controlled_loop', ['while', 'for', 'continue', 'break']),
             ('condition', ['if', 'elif', 'else']),
             ('debug', ['assert', 'raise']),
             ('exception', ['try', 'except', 'finally'])]

我打算使用以下代码大写每个元素元组中的前导字符串:

In [40]: list(map(lambda x:x[0].capitalize(), Keywords_33))
Out[40]:
['File',
 'Module',
 'Constant_3',
 'Operator_4',
 'Sequnce_operation_2',
 'Klass_1',
 'Function_7',
 'Controlled_loop',
 'Condition',
 'Debug',
 'Exception']

它只输出嵌套列表的部分内容。

我想要的输出是:

Keywords_33=[('File_2', ['with', 'as']),
             ('Module_2', ['from', 'import']),
             ('Constant_3', {'bool': ['False', 'True'],
                             'none': ['None']}),
             ('Operator_4', {'boolean_operation': {'or', 'and', 'not'},
                             'comparison': {'is'}}),
             ('Sequnce_operation_2', ['in', 'del']),
             ('Klass_1', ['class']),
             ('Function_7',['lambda', 'def', 'pass',
                            'global', 'nonlocal',
                            'return', 'yield']),
             ('Repetition_4', ['while', 'for', 'continue', 'break']),
             ('Condition_3', ['if', 'elif', 'else']),
             ('Debug_2', ['assert', 'raise']),
             ('Exception_3', ['try', 'except', 'finally'])]

我该如何改进?

1 个答案:

答案 0 :(得分:1)

您必须在3-10-14 1:06:05,9.74 3-10-14 1:08:02,10.44 3-10-14 1:09:20,9.83 3-10-14 1:11:53,10.49 中检索整个元组,然后将map仅应用于第一部分:

capitalize

在我看来,你应该避免list(map(lambda x:(x[0].capitalize(), x[1]), Keywords_33)) 并坚持列表理解:

map

您甚至可以使用拆包来使其更加优雅:

[(item[0].capitalize(), item[1]) for item in Keywords_33]