我有两组描述原子位置的数据。它们位于我想要比较的单独文件中,目的是通过坐标识别匹配的原子。这两种情况下的数据如下所示,并且条目数量最多为 1000 个左右。这些文件具有不同的长度,因为它们描述了不同大小的系统并具有以下格式:
1 , 0.000000000000E+00 0.000000000000E+00
2 , 0.000000000000E+00 2.468958660000E+00
3 , 0.000000000000E+00 -2.468958660000E+00
4 , 2.138180920454E+00 -1.234479330000E+00
5 , 2.138180920454E+00 1.234479330000E+00
第一列是条目 ID,第二列是 x,y 中的一组坐标。
我想要做的是比较两组数据中的坐标,识别匹配项和相应的 ID,例如“文件 1 中的条目 3 对应于文件 2 中的条目 6”。我将使用此信息来更改文件 2 中的坐标值。
我已经逐行读取了文件,并使用命令将它们分成每行两个条目,然后将它们放入列表中,但对于如何指定比较位有点困惑 - 特别是告诉它仅比较第二个条目,同时能够调用第一个条目。我想这需要循环?
到目前为止,代码如下所示:
open1 = open('./3x3supercell_coord_clean','r')
openA = open('./6x6supercell_coord_clean','r')
small_list=[]
for line in open1:
stripped_small_line = line.strip()
column_small = stripped_small_line.split(",")
small_list.append(column_small)
big_list=[]
for line in openA:
stripped_big_line = line.strip()
column_big = stripped_big_line.split(",")
big_list.append(column_big)
print small_list[2][1] #prints out coords only
最佳答案
使用以坐标为键的字典。
data1 = """1 , 0.000000000000E+00 0.000000000000E+00
2 , 0.000000000000E+00 2.468958660000E+00
3 , 0.000000000000E+00 -2.468958660000E+00
4 , 2.138180920454E+00 -1.234479330000E+00
5 , 2.138180920454E+00 1.234479330000E+00"""
# Read data1 into a list of tupes (id, x, y)
coords1 = [(int(line[0]), float(line[2]), float(line[3])) for line in
(line.split() for line in data1.split("\n"))]
# This dictionary will map (x, y) -> id
coordsToIds = {}
# Add coords1 to this dictionary.
for id, x, y in coords1:
coordsToIds[(x, y)] = id
# Read coords2 the same way.
# Left as an exercise to the reader.
# Look up each of coords2 in the dictionary.
for id, x, y in coords2:
if (x, y) in coordsToIds:
print(coordsToIds[(x, y)] # the ID in coords1
请注意,比较 float 始终是一个问题。
关于python - 使用 python 识别两个文件中的坐标匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16672448/