簡體   English   中英

類型錯誤:列表索引必須是整數或切片,而不是在 python 中使用 sys 導入的元組

[英]TypeError: list indices must be integers or slices, not tuple with sys import in python

在讀入數據時,Python 給了我以下錯誤:

類型錯誤:列表索引必須是整數或切片,而不是在 python 中使用 sys 導入的元組

我使用以下 data.txt 輸入文件:

1.0 2.0 3.0
4.0 5.0 6.0

使用命令 !python file_name data.txt import sys

fp = open(sys.argv[1],"r+")
coordinates = fp.readlines()
fp.close()

import numpy

a = numpy.array(coordinates[0, 1, 2])
b = numpy.array(coordinates[3, 4, 5])

dist_unround=numpy.linalg.norm(a-b)
dist_round=round(dist_unround, 2)

energy_unround=0.5*2*((dist_unround-3.0)**2)
energy_round=round(energy_unround,2)

print("dist \t energy")
print(dist_round,"\t" ,energy_round) 

我嘗試從隨機輸入文本文件中計算向量。 我的 numpy.array 代碼有問題嗎?

坐標是一個列表,並且您正試圖在a=行上傳遞元組0, 1 ,2

要正確使用方法,請更換

a = numpy.array(coordinates[0, 1, 2])
b = numpy.array(coordinates[3, 4, 5])

a = numpy.array(coordinates[0].split())
b = numpy.array(coordinates[1].split())

請注意, readlines返回一個字符串列表。 調用該列表( coordinates[0] )上的索引 0 以獲取第一組(行)值,然后對該字符串使用.split()方法使它們成為由空格分隔的字符串列表。

您可能希望在使用時將它們轉換為浮點數或整數。 如果你願意,可以用列表理解來做到這一點

a = numpy.array([int(x) for x in coordinates[0].split()])
b = numpy.array([int(x) for x in coordinates[1].split()])

從你提供的小細節來看,我猜這就是你要找的——

arr=[]
with open("data.txt") as f:
    for line in f:
        a=list(line.split(" "))
        for element in a:
            arr.append(float(element.rstrip()))
print(arr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM