python - 使用 python 从两个文件创建存在/不存在矩阵

标签 python

我有以下两个文件:

(一):

A01
A02
A03
A10
A11
C03
C10
C11
E01
E10
E11
H01
H02
H10
H11
Y09
Y10
Y11

(b):

E01  Y09  A02
A01  A03
C03  H01  H02
E10
Y10
A10
C10
H10
E11  A11  C11  H11  Y11

我试图根据这些数据创建一个存在/不存在矩阵,以查看 (a) 中的值是否存在于 (b) 中的行中。如果它们存在,则应由“1”表示,如果不存在,则应由“0”表示,其中“0”和“1”指示符遵循 (a) 中的值的顺序。

我的预期输出是:

0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0
1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1

我尝试过以下方法:

text_file = open("Table", "w")
a = file("list", "r")
b = file("cluster", "r")

for line in a:
    words = line.split("\n")
for line in b:
    words = line.split("\t")


for line in a:
    if words in a == words in b:
        print("1")
    elif words in a != words in b:
        print("0")
text_file.close

但是这不会打印任何内容。

有人可以帮忙吗?

最佳答案

我想我明白你想要什么。

final_matrix = []
a = file("list", "r")
a_list = []
# Make a list of all strings in the first file.
for line in a:
    a_list.append(line.rstrip())

b = file("cluster", "r")
for line in b:
    L1 = line.split('\t')
    # Make a presence/absence row for each line in the second file.
    this_row = [1 if i in L1 else 0 for i in a_list]
    final_matrix.append(this_row)

for row in final_matrix:
    print row
    # You can get fancier with this because right now it will
    # Print these out as lists.

在这种情况下,最终矩阵将保存为列表的列表。

关于python - 使用 python 从两个文件创建存在/不存在矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32015689/

相关文章:

python - 在 C++ 中返回 vector 中元素的第一个索引

python - 从 Pandas 数据框列中的对象中删除逗号

python - 使用 python 3.8+(默认协议(protocol) = 5)时,pickle.load 在来自 python 3.7 的(协议(protocol) = 4)对象上失败

python - 生成数字表

蟒龟 : trigger function on any key pressed

python - 如何更改 QPlainTextEdit 的光标形状(P​​yqt、PySide)

python - 如何编写一个函数来接受 SWIG 中的 Fraction 对象?

python - 如何在 ubuntu 的 cronjob 中运行 pipenv?

python - 为什么我不能按用户属性查询?

python - 接收 FileNotFoundError : [Errno 2] No such file or directory