删除python中元素的一部分
我正在通过API搜索(JSON格式)编写csv,我可以获取我需要的内容,但我的csv非常“脏”: 在我的csv文件中,我需要一个真正的标识符 我知道有.remove()函数,但我不知道如何使它与所有这些'and{一起工作 另外,我不知道它是否真的在csv.write函数中工作,和/或我忘记了代码中的某些内容:删除python中元素的一部分,python,json,csv,Python,Json,Csv,我正在通过API搜索(JSON格式)编写csv,我可以获取我需要的内容,但我的csv非常“脏”: 在我的csv文件中,我需要一个真正的标识符 我知道有.remove()函数,但我不知道如何使它与所有这些'and{一起工作 另外,我不知道它是否真的在csv.write函数中工作,和/或我忘记了代码中的某些内容: with open('test1.csv', 'wb') as file2: wr = csv.writer(file2) for result['identifier']
with open('test1.csv', 'wb') as file2:
wr = csv.writer(file2)
for result['identifier'] in search1:
time.sleep(10)
wr.writerow([result])
像这样的吗?:(测试)
比较的工作原理如下:
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
search1是通过APIYes搜索的定义,它真的很好!我只问你一件事:有没有办法同时剪切'和[]?那是因为我需要与其他干净的标识符进行比较,非常感谢!这只是一个元素列表,你可以用res[0]访问它们等等。添加了比较示例。是的,对不起,我的意思是我需要将此列表与另一个csv中的另一个列表进行比较,但是“干净”。如下所示:csv1=identifier1,identifier2,identifier3,identifier4 csv2(来自API)=['identifier3'],['identifier1'],['identifier4']我在考虑使用difflib,它可以识别它吗?理解你的意思有点困难,但我还是会试试。
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