Python “方法”对象的问题不可下标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34701698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problems with 'method' object is not subscriptable
提问by Aurora_Titanium
I have a textfile which contains
我有一个文本文件,其中包含
id_is_g0000515
num_is_0.92
id_is_g0000774
num_is_1.04
id_is_g0000377
num_is_1.01
id_is_g0000521
num_is_5.6
id_is_g0000515
num_is_0.92
id_is_g0000774
num_is_1.04
id_is_g0000377
num_is_1.01
id_is_g0000521
num_is_5.6
Its suppose to sort the data in by "g0000515" and by numbers only "0.92" without the string "id_is_" and "num_is_". It gives me an error TypeError: 'method' object is not subscriptable. Can someone help me?
它假设按“g0000515”和仅按数字“0.92”对数据进行排序,而没有字符串“id_is_”和“num_is_”。它给了我一个错误 TypeError: 'method' object is not subscriptable。有人能帮我吗?
import os, sys, shutil, re
def readFile():
from queue import PriorityQueue
q = PriorityQueue()
#try block will execute if the text file is found
try:
fileName= open("Real_format.txt",'r')
#for tuple in fileName:
#fileName.write('%s',tuple)
for line in fileName:
for string in line.strip().split(','):
if string.find("id_is_"):
q.put[-4:] #read the ID only as g0000774
elif string.find("num_is_"):
q.put[-4:] #read the num only as 0.92
fileName.close() #close the file after reading
print("Displaying Sorted Data")
#print("ID TYPE Type")
while not q.empty():
print(string[30:35] + ": " +q.get())
#print(q.get())
#catch block will execute if no text file is found
except IOError:
print("Error: FileNotFoundException")
return
readFile()
回答by Martijn Pieters
You are trying to slice the PriorityQueue.put()
method here:
您正在尝试在PriorityQueue.put()
此处对方法进行切片:
q.put[-4:]
That won't work; method objects are not sliceable. I think you wanted to slice the string
variable and put all but the first 4 characters in the queue instead:
那行不通;方法对象不可切片。我认为您想对string
变量进行切片并将除前 4 个字符之外的所有字符都放入队列中:
q.put(string[4:])
Note that I used a positivenumber there; you don't want the list 4 characters, you want everything but the first 4.
请注意,我在那里使用了正数;您不想要列表 4 个字符,您想要除前 4 个字符以外的所有字符。
When the string starts with "num_is_"
, you'll need to skip more characters; num_is_
is 7 characters, not 4:
当字符串以 开头时"num_is_"
,您需要跳过更多字符;num_is_
是 7 个字符,而不是 4 个:
q.put(string[7:])