Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较Excel中的输入并写入.txt文件_Python_Excel - Fatal编程技术网

Python 比较Excel中的输入并写入.txt文件

Python 比较Excel中的输入并写入.txt文件,python,excel,Python,Excel,我在Excel中有如下输入: Column1 Column2 1 test1 1 test2 2 test3 2 test4 2 test5 test1 test2 test3 test4 test5 我的目标是比较column1的数字,如果它们相等,则将column2字符串连接到列表,并在之间留有空格,然后将列表写入.txt文件。 基本上,结果应该在.txt文件中,如下所示: Column1 Column2 1 tes

我在Excel中有如下输入:

Column1 Column2
1       test1
1       test2
2       test3
2       test4
2       test5
test1 test2
test3 test4 test5
我的目标是比较column1的数字,如果它们相等,则将column2字符串连接到列表,并在之间留有空格,然后将列表写入.txt文件。 基本上,结果应该在.txt文件中,如下所示:

Column1 Column2
1       test1
1       test2
2       test3
2       test4
2       test5
test1 test2
test3 test4 test5
我需要关于最后一部分的帮助,即写入新列表或文件,其中字符串用空格连接和分隔。如果数字发生变化(如从1变为2),则新字符串应位于文件/列表的新行上

目前,如果你有这么多:

import xlrd
from os import sys

workbook = xlrd.open_workbook("test.xls")
worksheet = workbook.sheet_by_index(0)

col1 = []
col2 = []
out = []
col1.append(worksheet.col_values(0))
col2.append(worksheet.col_values(1))
n = 0
m = 1
for n in range(len(col1)):
    for m in range(len(col1)):
        if col1[n] == col1[m]:
            out.append(col2[n])
    m += 1
n += 1
print '%s' % out

可以使用字典获取具有相同int值的所有项。最后,将列表项作为字符串打印到文本文件中。我张贴的代码为您的最后一部分,需要改变

from collections import defaultdict
res_dict = defaultdict(list)

for n in range(len(col1)):
  res_dict[col1[n]].append(col2[n])

for key, val_list in res_dict.items():
  text_file_handle.write(' '.join(val_list) + '\n')

它给了我一个错误:res_dict[col1[n]].append(col2[n])TypeError:unhable type:'list'将列表转换为字典?什么是
col1[n]
。您可以在for循环中打印它并在此处发布。对于范围内的n(len(col1)):打印“%s”%col1[n]发出:[1.0、1.0、2.0、2.0、2.0]您可以在access中使用交叉表查询来执行此操作。除非您希望批处理多个excel文件,否则不需要python。您可能需要添加第三列,但我认为这是可以做到的。我只是想用python来做,一定要进一步了解它。