Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.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中的表匹配_Python - Fatal编程技术网

python中的表匹配

python中的表匹配,python,Python,我有以下问题: 我有两个表(txt/csv),有两列(第一列位置x,第二列位置y),它们是一对 必须读取T表并匹配值:因此必须将表1中的每个x-y对与表2中的每个x-y对进行比较。如果存在任何匹配项,则必须创建一个新表 我已经在TopCat中这样做了,但是在Python中需要它(我使用Python2.7)。但是,这些值的四舍五入不相等,如果我匹配它们,则没有匹配对(例如1.2398&3.9735,1.239857&3.973522) 任何帮助都将不胜感激 四舍五入到小数点后4位的另一种方法是执行

我有以下问题:

我有两个表(
txt
/
csv
),有两列(第一列位置x,第二列位置y),它们是一对

必须读取T表并匹配值:因此必须将表1中的每个x-y对与表2中的每个x-y对进行比较。如果存在任何匹配项,则必须创建一个新表

我已经在
TopCat
中这样做了,但是在Python中需要它(我使用Python
2.7
)。但是,这些值的四舍五入不相等,如果我匹配它们,则没有匹配对(例如
1.2398
&
3.9735
1.239857
&
3.973522


任何帮助都将不胜感激

四舍五入到小数点后4位的另一种方法是执行:
'%0.4f'%float(1.239857)
,其中输出为
1.2399

对于您的问题,由于我有足够的时间,您可以使用/参考:

def get_coordinates(infile, delimiter):
    new_list = []
    with open(infile, 'r') as f:
        for line in f:
            x, y = [float(i) for i in line.strip().split(delimiter)]

            ## rounding happens here: 4 decimal places for x and y
            new_list.append('%0.4f,%0.4f' % (x, y))

    return new_list


## Extract x,y coordinates from input file given delimiter 
LIST1 = get_coordinates('table1.txt', ',')
LIST2 = get_coordinates('table2.txt', ',')

## New list with common coordinates between the two file
NEW_LIST = list(set(LIST1) & set(LIST2))

## print result to output file: "outfile.txt"
with open('outfile.txt', 'w') as outfile:
    for xy in NEW_LIST:
        ## write entries "x,y" -- this the default
        outfile.write('%s\n' % xy)

        ## -----------------------------------------------------
        ## by default it will be CSV, but
        ## if you want to split by tabs then
        ## comment out previous part & uncomment the following:
        ## -----------------------------------------------------

        # outfile.write('%s\n' % '\t'.join(xy.split(',')))

我没有时间回答真正的问题,但是。。。但这是有区别的。使用
round
也可以很好地。。。对结果进行四舍五入,而您的解决方案只需将浮点转换为字符串,并在点后4位对其进行切片。我不确定OPI的首选选项是什么,我认为这种方法首先将浮点值舍入到点后的4位,然后将其转换为字符串。。。因为
'%0.4f'%0.999999999
产生
'1.0000'
而不是'0.9999':)哦,好的。奇怪,我不知道。看起来有点不直观。除了格式化字符串,为什么字符串格式化还能做其他事情?我想知道它是否使用了与
round
相同的功能,如果不是,您是否总能得到相同的结果。。。这很有趣……没问题,但欢迎你接受我的回答;)当我运行程序时,我在以下行中得到“ValueError:-->204 builtin.execfile(文件名,*where);-->18 LIST1=get_坐标('table1.txt',',')和-->9 x,y=[float(i)for i in line.strip().split('delimiter')]按该顺序排列。最后一行是:222.27515,8.0208306eral for float():222.30777,8.9363889我不明白这为什么不能正常工作…