Python 给出空列表的词典上的列表理解
我有一本字典如下:Python 给出空列表的词典上的列表理解,python,dictionary,list-comprehension,Python,Dictionary,List Comprehension,我有一本字典如下: 'give': (('VBP', 6), ('VB', 15)), 'discounts': ('NNS', 1), 'maintaining': ('VBG', 4), 'increasing': ('VBG', 18), 'spending': (('NN', 24), ('VBG', 2)), 'become': ((('VBN', 7), ('VB', 15)), ('VBP', 1)), 'permanent': ('JJ', 2), 'fixtur
'give': (('VBP', 6), ('VB', 15)),
'discounts': ('NNS', 1),
'maintaining': ('VBG', 4),
'increasing': ('VBG', 18),
'spending': (('NN', 24), ('VBG', 2)),
'become': ((('VBN', 7), ('VB', 15)), ('VBP', 1)),
'permanent': ('JJ', 2),
'fixtures': ('NNS', 1),
'news': ('NN', 24),
'weeklies': ('NNS', 2),
'underscore': ('VBP', 1),
'fierce': ('JJ', 2),
'competition': ('NN', 10)
result = [x for x in mydict.items() if type(x[1][0]) == 'str']
我正在写一份清单,如下所示:
'give': (('VBP', 6), ('VB', 15)),
'discounts': ('NNS', 1),
'maintaining': ('VBG', 4),
'increasing': ('VBG', 18),
'spending': (('NN', 24), ('VBG', 2)),
'become': ((('VBN', 7), ('VB', 15)), ('VBP', 1)),
'permanent': ('JJ', 2),
'fixtures': ('NNS', 1),
'news': ('NN', 24),
'weeklies': ('NNS', 2),
'underscore': ('VBP', 1),
'fierce': ('JJ', 2),
'competition': ('NN', 10)
result = [x for x in mydict.items() if type(x[1][0]) == 'str']
但这会导致一个空列表,而如果我看到字典中有许多元素,那么这个条件就满足了。或者你可以将
'str'
更改为str
,即
result = [x for x in mydict.items() if type(x[1][0]) == str]
或者,您可以尝试使用isinstance
方法检查它是否是string
()的实例:
结果:
['increasing', 'maintaining', 'fierce', 'permanent', 'fixtures', 'underscore', 'news', 'weeklies', 'discounts', 'become', 'give', 'competition', 'spending']
类型不是字符串而是类。你想做什么?预期产量是多少?您可以使用
type(var)is str
进行类型匹配。@因此最好使用isinstance()
函数。