我有三个表,需要创建第四个表来对前三个表中的所有信息进行分组。你知道吗
文件1:包含表4的相关键。file1.txt:
a namex 23 14
b nameY 30 18
c nameZ 10 20
文件2:根据[2]从[1]和[3]收集信息。
生成如下字典:
DICT2={'X':['nameX','infoX'],'Y':['nameY','infoY'],'Z':['nameZ','infoZ']}
file2.txt:
[0] [1] [2] [3] [4] [5]
idX nameX X infoX ... descriptionX
idY nameY Y infoY ... descriptionY
idZ nameZ Z infoZ ... descriptionZ
文件3:“a”、“b”和“c”的值用于附加到DICT1的末尾。
file3.txt
a 1 0 1 0 0
b 0 3 8 2 0
c 3 5 3 4 1
我的剧本:
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')
file3 = open('file3.txt', 'r')
DICT1 = {}
DICT2 = {}
DICT3 = {}
for line in file1:
row = line.strip().split('\t')
if row[0] not in DICT1:
DICT1[row[0]] = row[1:]
for line2 in file2:
row2 = line2.strip().split('\t')
if row2[1] not in DICT2:
DICT2[row2[1]] = row2[2], row2[5]
for line3 in file3:
row3 = line3.strip().split('\t')
name = line3[0].strip()
count = line3[1:]
if name not in DICT3:
DICT3[name] = count
if name in DICT1 and DICT2:
print(name + '\t' + DICT2[key] + str('\t'.join(count)) + '\t' +
str('\t'.join(DICT1[name])))
当我尝试将DICT3中的值包含到print中时,DICT2中的第一个键会重复到all(表中的X):
a X 1 0 1 0 0 nameX 23 14
b X 0 3 8 2 0 nameY 30 18
c X 3 5 3 4 1 nameZ 10 20
我想得到的输出如下:
a X 1 0 1 0 0 nameX 23 14
b Y 0 3 8 2 0 nameY 30 18
c Z 3 5 3 4 1 nameZ 10 20
先谢谢你。你知道吗
我们先开始清理代码,看看能不能找到你想要的地方
首先,您有带有分隔数据的文本文件。在任何时候,您都应该使用
csv
模块来解析它。如果您有一个stdlib模块为您执行此操作,请不要尝试按行读取并使用分隔符拆分。很容易出现意外的实现错误。你知道吗其次,使用
with
关键字打开文件。这样可以避免你以后不得不关闭它们(可能会忘记),这是一个很好的做法。你知道吗现在让我们看看您是如何创建这些词典的。有很多
if key not in dict: dict[key] = data
。你真的认为你会有重复的数据而忽略其余的吗?如果是这样,很好,继续做下去!如果没有,放下它,做:现在我们已经将所有数据制成表格,我们可以生成一个输出:
那个又大又丑的东西应该会给你正确的结果,尽管你必须加入字符串才能做到。你知道吗
你的代码
你的代码有很多错误,这使得你很难去分析到底出了什么问题。像
DICT2.key[]
这样的东西在你最后的打印行中可能是DICT2.keys()
,但是应该会抛出错误消息,你没有报告,如果提供的代码不是编写的代码,我会犹豫猜测出了什么问题!你知道吗相关问题 更多 >
编程相关推荐