Python中两列之间的计算?

2024-04-20 01:49:37 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试在两列之间进行一些计算(如除法)时,我得到一个错误:column_ratio[x]=(float(column1[y]))/(float(column2[z])) TypeError: tuple indices must be integers, not str。有人能帮我解决这个问题吗?你知道吗

from itertools import izip_longest
import csv
with open(r"C:\Users\a.txt", 'rb') as csv1,\
 open(r"C:\Users\b.txt", 'rb') as csv2, \
 open(r"C:\Users\c.txt", 'rb') as csv3, \
 open(r"C:\Users\out.txt", 'w') as out:

    spam1 = csv.reader(csv1, delimiter=',')
    spam2 = csv.reader(csv2, delimiter=',')
    spam3= csv.reader(csv3, delimiter=',')

    column1=list(izip_longest(*spam1))[-1]
    column2=list(izip_longest(*spam2))[-1]
    column3=list(izip_longest(*spam3))[-1]

    column_ratio=[]
    for x,y,z in izip_longest(column_ratio, column1, column2):
        column_ratio[x]=(float(column1[y]))/(float(column2[z]))

    for i,j,m,n,x in izip_longest(spam1,column1, column2, column3, column_ratio):
        out.write(','.join(i)+','+j+','+m+','+n+','+x+'\n')

Tags: csvtxtlongestascolumnopenfloatout
1条回答
网友
1楼 · 发布于 2024-04-20 01:49:37

当您使用CSV读取器进行解析时,它无法知道数据应该是整数、浮点数、字符串等。所有以逗号分隔的数据都被解析为字符串,并由您将其转换为正确的类型。您需要将字符串强制为整数才能将其用作索引。你知道吗


采取以下措施:

Index One, Index Two, Index Three
0,1,2

解析时:

x, y, z = reader.next()  # ['0', '1', '2']
print my_tuple[x]  # TypeError: tuple indices must be integers, not str
print my_tuple[int(x)]  # Expected result

相关问题 更多 >