[英]Python initialize class with list
I have to initialize class with list, which will return every sublists from the given list.我必须用列表初始化类,它将返回给定列表中的每个子列表。
I have a problem with defining empty list as an argument:我在将空列表定义为参数时遇到问题:
class list():
def sublists(self, lst=[]):
sub = [[]]
for i in range(len(lst)+1):
for j in range (i+1, len(lst)):
sub = lst[i:j]
sub.append(sub)
return sub
As others have pointed out, your intention is not quite clear from the question.正如其他人所指出的那样,您的意图从问题中并不十分清楚。 What I understood is that you want to get all contiguous sublists of a given list.
我的理解是您想要获取给定列表的所有连续子列表。
This achieves that.这实现了。
class MyList:
def sublists(self, lst=[]):
subs = [[]]
for i in range(len(lst)):
for j in range (i+1, len(lst)+1):
sub = lst[i:j]
subs.append(sub)
return subs
x = [i for i in range(3)]
my_list = MyList()
print(my_list.sublists(x))
Please update your question if you intend to do something else.如果您打算做其他事情,请更新您的问题。
Correct me if I'm wrong, but I guess the task is quite simple.如果我错了,请纠正我,但我想任务很简单。 You can just init your class instance with the list:
您可以使用列表初始化您的类实例:
class list():
sub = []
def __init__(self, lst=[]):
self.sub = lst
a = [
[1,2,3],
[4,5,6],
[7,8,9],
]
myClass = list(a)
print(myClass.sub)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.