gpt4 book ai didi

python - 在python中删除部分元素

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:22 25 4
gpt4 key购买 nike

我正在通过 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])

最佳答案

是这样的吗?:(测试 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

关于python - 在python中删除部分元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32246841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com