typeerror:cannot import name 'Iterable' from 'collections'

第一个文件:die.py
from random import randint
‘’’创建掷骰子类’’’
class Die():
def init(self,num_sides=6):
self.num_sides=num_sides
def roll(self):
return randint(1,self.num_sides)

第二个文件:visual.py
from die import Die
‘’’创建实例’’’
die=Die()
results=[]
for roll_num in range(100):
result=die.roll()
results.append(result)
frequencies=[]
for value in range(1,die.num_sides+1):
frequency=results.count(value)
frequencies.append(frequency)

import pygal
hist=pygal.Bar()
hist.title(‘掷骰子100子’)
hist.x_labels=[‘1’,’2’,’3’,’4’,’5’,’6’]
hist.x_title=’结果’
hist.y_title=’结果的频次’
hist.add(‘D6’,frequencies)
hist.render_to_file(‘die_visual.svg’)

讨论数量: 4
Jason990420

typeerror ? 应该是 ImportError ?

Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Iterable
<stdin>:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working

这个问题好像在 pygal 2.4.0 已经解决了。妳的 Python是 3.10 的吗 ? 像这样的问题,应该要提供各相关软件的版本,如OS,Python,Library等.

在我的 WIN10, Python 3.95, pygal 2.4.0 运行以下代码没有问题

# die.py

from random import randint

class Die():

    '''创建掷骰子类'''

    def __init__(self,num_sides=6):
        self.num_sides=num_sides

    def roll(self):
        return randint(1, self.num_sides)
# visual.py

import pygal
from die import Die

die = Die()     # 创建实例

results     = [die.roll() for roll_num in range(100)]
frequencies = [results.count(value) for value in range(1, die.num_sides + 1)]

hist = pygal.Bar()
hist.title = '掷骰子 100 子'
hist.x_title = '结果'
hist.y_title = '结果的频次'
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')

2周前 评论
Tina_J (楼主) 1周前
Jason990420

自 Python 3.10 開始, 庫 collections 以下各項都停用了, 其中就包含了 pygal._compat.py 中的 from collections import Iterator

["Awaitable", "Coroutine", "AsyncIterable", "AsyncIterator", "AsyncGenerator", "Hashable", "Iterable", "Iterator", "Generator", "Reversible", "Sized", "Container", "Callable", "Collection", "Set", "MutableSet", "Mapping", "MutableMapping", "MappingView", "KeysView", "ItemsView", "ValuesView", "Sequence", "MutableSequence", "ByteString"]

pygal 在 pypi 的最新版本為 2.4.0, 但是它的 pygal._compat.py 更新並没有加入

github.com/Kozea/pygal/blob/master...

更新的內容為

github.com/Kozea/pygal/commit/7796...

因此, 必須自己更改 Lib\site-packages\pygal_compat.py` 的內容

# from collections import Iterable        # Line 23
try:
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable
1周前 评论
Jason990420

pygal 今天已经在 pypi 中升级到 3.0.0,所以你可以从 pypi 升级它,这个问题将得到解决。

1周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!