【问题标题】:list comprehension on a dictionary giving empty list字典上的列表理解给出空列表
【发布时间】:2018-04-14 03:22:08
【问题描述】:

我有一本字典如下:

 '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']

但这会导致一个空列表,而如果我看到字典中有很多元素,则满足此条件。

【问题讨论】:

  • 类型不是字符串而是类。
  • 你想做什么?什么是预期的输出?您可以使用type(var) is str 进行类型匹配。
  • @arsho 最好使用isinstance()函数。

标签: python dictionary list-comprehension


【解决方案1】:

您可以将'str' 更改为str

result = [x for x in mydict.items() if type(x[1][0]) == str]

或者您可以尝试使用isinstance 方法来检查它是否是string (details) 的实例:

result = [x for x,value in mydict.items() if isinstance(x[1][0],str)]
print(result)

结果:

['increasing', 'maintaining', 'fierce', 'permanent', 'fixtures', 'underscore', 'news', 'weeklies', 'discounts', 'become', 'give', 'competition', 'spending']

【讨论】:

    猜你喜欢
    • 2022-12-13
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多