根据变量值在列表内创建列表

时间:2019-12-08 07:44:55

标签: python python-3.x list

我想在列表中创建一个列表。这两个列表均具有预定义的元素数量。 例如。

num_of_class=5
num_of_subjects=[5,6,4,2,3] #the length of this list is dependent on the value of num_of_class.


outside_list=[] #I want this list to have 5 lists depending on value of num_of_class also

现在,我希望在外部列表中包含5个(取决于num_of_class的值)列表,该列表将根据列表中num_of_subjects个元素的值获取其中的元素数量。

输出示例

outside_list=[[a,a,a,a,a],[b,b,b,b,b,b],[c,c,c,c],[d,d],[e,e,e]]

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

num_of_class=5
num_of_subjects=[5,6,4,2,3] #the length of this list is dependent on the value of num_of_class.

outside_list=[] #I want this # list to have 5 lists depending on value of num_of_class also
for n in num_of_subjects:
    inp = input('what is the input?')
    outside_list.append([inp for i in range(n)])

如果您希望内部列表中的元素可能不同,则可以在for n in num_of_subjects循环中添加另一个内部循环,如下所示:

num_of_class=5
num_of_subjects=[5,6,4,2,3] #the length of this list is dependent on the value of num_of_class.
outside_list=[] #I want this # list to have 5 lists depending on value of num_of_class also
for n in num_of_subjects:
    inside_list = []
    for j in range(n): 
        inp = input('what is the subject')
        inside_list.append(inp)
    outside_list.append(inside_list)

其输出如下:

Out[31]: 
[['a', 'b', 'c', 'd', 'e'],
 ['f', 'g', 'h', 'i', 'j', 'k'],
 ['l', 'm', 'n', 'o'],
 ['p', 'q'],
 ['r', 's', 't']]

答案 1 :(得分:0)

num_of_subjects = [1,2,3,4]
outer_list = []

for classnum, outside in enumerate(lensub, 1):
    for inside in range(outside):
        subjinput = input("Enter subjects for class %d" % classnum)
        outer_list.append([subjinput for n in range(outside)])

这需要输入的数量取决于num_of_subjects中存在的元素值,在此之后,我完全迷失了代码。