【问题标题】:How do you check whether a list contains a dictionary inside?如何检查列表中是否包含字典?
【发布时间】:2021-05-18 08:51:05
【问题描述】:

我有一个代码可以检查一列是否包含一个列表,如果发现它会分解该列表并将分解的列转换为int(如果它是数字)。但是,我遇到了一个问题,因为我的文件中的某些列表包含字典。我如何将它包含到我现有的代码中以检查列表是否包含字典/键,如果是,它不应该分解该列并保持原样。

当前代码:

x = (doc.applymap(type) == list).all()
y = x.index[x].tolist()
for i in y:
    doc= doc.explode(i)
    if (doc[i].str.isnumeric().all()) == True:
        x = (doc[i].to_frame().columns)
        doc[x] = doc[x].fillna(0).astype(int)

输入:

ID

"number": [1,2,3,4],
"number": [{"enabled": 1,2,3,4}]

预期输出

ID
1
2
3
4
[{"enabled": 1,2,3,4}]

【问题讨论】:

  • 这个问题略有不同,它检查它是否是一本字典,我的一个是检查字典是否真的在列表中
  • 然后迭代所有列表项并检查每个项是否为字典?找到字典后,您可以停止检查。
  • 所以您想知道您是在爆炸字典还是列表,对吗?只需进行两步检查吗?无论如何,你能提供你的数据样本吗?
  • 我已经包含了一个关于输入和输出应该是什么样的想法,所以是的,应该有一个两步检查,检查列是否包含我已经完成的列表, 但然后检查该列表是否包含字典,如果包含则打印它,如果它不包含字典,则分解列

标签: python pandas list dictionary


【解决方案1】:

可能不是最好的方法,但这样做可以:

for i in y:
    m = str(doc[i][0]).strip('[]')
    if m[0] == '{' and m[-1] == '}':
        pass
    else:
        doc = doc.explode(i)
        if (doc[i].str.isnumeric().all()) == True:
            x = (doc[i].to_frame().columns)
            doc[x] = doc[x].fillna(0).astype(int)

【讨论】:

    【解决方案2】:

    我不完全确定您要做什么,但这是您可以检查字典是否在列表中的方法。

    如果列表包含字典,上面的仅返回TrueFalse,第二个为您提供项目本身。

    mylist = [1, 2, 3,{"key":"value"} 4, 5]
    if any(type(x) is dict for x in mylist):
        #List contains a dict
    else:
        #do other stuff
    
    
    for x in mylist:
        item_type = type(x)
        if(item_type is dict):
            #item is dict
        else:
            #item is not dict
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2020-07-10
      • 2017-02-27
      • 2018-07-24
      • 2017-02-10
      • 2022-12-13
      • 2013-01-01
      相关资源
      最近更新 更多