在我导入itertools之后,我在下面的代码上运行itertools.accumulate(),我得到一个错误,说-
Traceback (most recent call last):
File "Equal_Stacks.py", line 36, in <module>
result = equalStacks(h1 , h2 , h3)
File "Equal_Stacks.py", line 8, in equalStacks
h11 = itertools.accumulate(h1)
AttributeError: 'module' object has no attribute 'accumulate'但是,当我在解释器中运行itertools.accumulate()函数时,它工作得很好。
import sys
import itertools
def equalStacks(h1 , h2 , h3):
h11 = itertools.accumulate(h1)
h22 = itertools.accumulate(h2)
h33 = itertools.accumulate(h3)
equal = False
while not equal:
if h11[-1] == h22[-1] == h33[-1]:
equal = True
break
else:
if h11[-1] > h22[-1] and h11[-1] > h33[-1] and len(h11) != 0:
h11.pop()
elif h22[-1] > h11[-1] and h22[-1] > h33[-1] and len(h22) != 0:
h22.pop()
elif h33[-1] > h11[-1] and h33[-1] > h22[-1] and len(h33) != 0:
h33.pop()
return str(h11[-1])
if __name__ == '__main__':
n1 , n2 , n3 = map( int , sys.stdin.readline().strip().split() )
h1 = list( map( int, sys.stdin.readline().strip().split() ) )
h2 = list( map( int, sys.stdin.readline().strip().split() ) )
h3 = list( map( int, sys.stdin.readline().strip().split() ) )
result = equalStacks(h1 , h2 , h3)
_ = sys.stdout.write( result + '\n')发布于 2020-01-19 08:59:25
我只是在我的编辑器上复制了你的代码,然后我得到了这个,这看起来不太对劲:
h11: Iterator
Value 'h11' is unsubscriptablepylint(unsubscriptable-object)然后我尝试用输入来执行你的代码,我得到了一个类似于你的错误,但它说:
Traceback (most recent call last):
File "c:/Users/Chechu/Desktop/s.py", line 33, in <module>
result = equalStacks(h1 , h2 , h3)
File "c:/Users/Chechu/Desktop/s.py", line 13, in equalStacks
if h11[-1] == h22[-1] == h33[-1]:
TypeError: 'itertools.accumulate' object is not subscriptable正如您所看到的,堆积工作的代码行很好(您也可以使用see the documentation)。
我认为你误解了迭代器是什么,因为你不能从它访问元素。您必须进行强制转换,以列表到该迭代器。你的代码只需要:
h11 = list(itertools.accumulate(h1))
h22 = list(itertools.accumulate(h2))
h33 = list(itertools.accumulate(h3))发布于 2020-07-26 13:37:19
确保您使用的是正确的python版本。python和python3是有区别的。
python调用python2.,而python3调用python3..累加模块仅在python3中可用
https://stackoverflow.com/questions/59798055
复制相似问题