Tôi có một danh sách chứa số id. Một số yếu tố của danh sách là một danh sách khác. Để chuyển đổi danh sách lồng nhau thành một danh sách, tôi viết hàm đệ quy bằng mô đun bộ sưu tập.
Mã của tôi đang theo dõi.
from collections import Iterable
def single_list(list):
for item in list:
if isinstance(item, Iterable):
yield from single_list(item)
else:
yield item
Item_list = [10,20,[30,40],[50,'Null',70],100]
items_single=single_list(Item_list)
for item in items_single:
print(item)
Khi tôi chạy chương trình của mình, tôi nhận được thông báo lỗi sau.
Traceback (most recent call last):
File "/Research/SoftDev/SEPJ/StackOverflow_qs.py", line 42, in <module>
for i in items_single:
File "/Research/SoftDev/SEPJ/StackOverflow_qs.py", line 36, in single_list
yield from single_list(item)
File "/Research/SoftDev/SEPJ/StackOverflow_qs.py", line 36, in single_list
yield from single_list(item)
File "/Research/SoftDev/SEPJ/StackOverflow_qs.py", line 36, in single_list
yield from single_list(item)
[Previous line repeated 986 more times]
File "/Research/SoftDev/SEPJ/StackOverflow_qs.py", line 35, in single_list
if isinstance(item, Iterable):
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/abc.py", line 184, in __instancecheck__
if subclass in cls._abc_cache:
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_weakrefset.py", line 75, in __contains__
return wr in self.data
RecursionError: maximum recursion depth exceeded in comparison
Process finished with exit code 1
Tôi không biết làm thế nào để sửa lỗi.
mpu.datastructures.flatten(yourlist)
như là một giải pháp cho vấn đề - bạn cũng có thể nhìn vào việc thực hiện.