【问题标题】:Remove part of an element in python在python中删除部分元素
【发布时间】:2015-08-27 10:23:34
【问题描述】:

我正在通过 API 搜索(JSON 格式)编写 csv,我可以获取我需要的内容,但我的 csv 非常“脏”:

{u'identifier': {u'identifier': u'the_real_identifier'}}

我需要在我的 csv 文件中只有 the_real_identifier

我知道有 .remove() 函数,但我不知道如何使它适用于所有这些 ' 和 {。

另外我不知道它是否真的在 csv.write 函数中工作和/或我忘记了我的代码中的某些内容:

with open('test1.csv', 'wb') as file2:
    wr = csv.writer(file2)
    for result['identifier'] in search1: 
        time.sleep(10)
        wr.writerow([result])

【问题讨论】:

  • search1 是 API 搜索的定义

标签: python json csv


【解决方案1】:

类似这样的东西?:(测试here

d={u'identifier': {u'identifier': u'the_real_identifier'},
   u'identifier1': {u'identifier1': u'the_real_identifier1'}}
res = [value[key] for key,value in d.items()]
print(res)
# ['the_real_identifier', 'the_real_identifier1']

比较的工作方式如下:

if(res[0]=='the_real_identifier'):print("identified")
if(res[1]=='the_real_identifier1'):print("also identified")

或者,如果您想要所有结果:

for item in res:
    print(item)

#the_real_identifier
#the_real_identifier1

按照评论中的要求:

csv1 = "identifier1, identifier2, identifier3, identifier4"
csv2 = [['identifier3'], ['identifier1'], ['identifier4'], ['new_item_4']]

data = [item.strip() for item in csv1.split(",")]

for item in csv2:
    real_item = item[0]
    if real_item not in data:
        #this is a new one, we could add it to data
        data.append(real_item)


print(", ".join(data))
#identifier1, identifier2, identifier3, identifier4, new_item_4

【讨论】:

  • 是的,真的很好!我只问你一件事:有没有办法同时削减 ' 和 [ ]?那是因为我需要与其他干净的标识符进行比较非常感谢!
  • 嗯,这只是一个元素列表,你可以通过 res[0] 等来访问它们。添加了比较示例。
  • 是的,抱歉,我的意思是我需要将此列表与另一个 csv 中的另一个列表进行比较,但要“干净”。是这样的: csv1 = identifier1, identifier2, identifier3, identifier4 csv2 (from API) = ['identifier3'], ['identifier1'], ['identifier4'] 我在想用difflib,反正它也能识别?
  • 有点难理解你的意思,不过我还是试试看。
猜你喜欢
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多