gpt4 book ai didi

Python 创建一个字典并将它们交换到另一个文件中

转载 作者:行者123 更新时间:2023-11-28 17:54:35 30 4
gpt4 key购买 nike

我有两个制表符分隔的 .csv 文件。我从 one.csv 创建了一个字典,如下所示:

'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n',
'EB3128': ' "\t"yagE "\t\t"b0268 "\n',
'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n',
'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n',

我想将字典的值插入到 second.csv 文件中,如下所示:

"EB2430"    36.81   364 222 4   72  430 101 461 1.00E-063   237
"EB3128" 26.04 169 108 6 42 206 17 172 6.00E-006 45.8
"EB3945" 20.6 233 162 6 106 333 33 247 6.00E-005 42.4
"EB3944" 19.07 367 284 6 1 355 1 366 2.00E-023 103

结果输出制表符分隔:

'EB2430'   idnD   yjgV   b4267   36.81   364 222 4   72  430 101 461 1.00E-063   237
'EB3128' yagE b0268 26.04 169 108 6 42 206 17 172 6.00E-006 45.8
'EB3945' maeB ypfF b2463 20.6 233 162 6 106 333 33 247 6.00E-005 42.4
'EB3944' eutS ypfE b2462 19.07 367 284 6 1 355 1 366 2.00E-023 103

这是我创建字典的代码:

f = open ("one.csv", "r")
g = open ("second.csv", "r")
eb = []
desc = []
di = {}

for line in f:
for row in f:
eb.append(row[1:7])
desc.append(row[7:])

di = dict(zip(eb,desc))

抱歉这么啰嗦!!我编程时间不长。

干杯!

星期六

最佳答案

看起来您可以更有用地使用 Python 标准库 csv模块在这里。而不是自己“手动”执行文本处理部分。例如:

import csv
with open("one.csv", "r") as f:
rows_one = list(csv.reader(f, delimiter='\t'))
with open("second.csv", "r") as g:
rows_two = list(csv.reader(g, delimiter='\t'))
rows_totl = [r + s[1:] for r, s in zip(rows_one, rows_two)]
with open("total.csv", "w") as h:
csv.writer(h, delimiter='\t').writerows(rows_totl)

with 语句是 Python 2.6 的瑰宝之一(它在 2.5 中也可用,但前提是您 from __future__ import with_statement!-)——如所用在这里,它为您提供了一个打开的文件,并确保它在 with 主体完成后立即关闭...此外,它还有更多用途,例如用于锁和各种您自己的自定义编码的“上下文管理器”。

关于Python 创建一个字典并将它们交换到另一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2563088/

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