我想从列表中读取特定数量的行并将所有这些值分配给一个新列表。然后我想从之前的last_value+1行中读取下一组完全相同的行数,并将它们分配给一个新列表。到目前为止我有这个:
假设 u = [1,2,3....,9,10,11,12,13...,19,20]
我想分配前 10 个将 u
中的值放入新生成的 list1 = [] => list1 = [1,2,..9,10]
然后我希望将 u
中的接下来 10 个值分配给 list2
,因此 list2 = [11,12,13..,20]
.到目前为止的代码是:
nLines = 10
nrepeats = 2
j=0
i=0
while (j<nrepeats):
### Generating empty lists ###
mklist = "list" + str(j) + " = []"
### do the segmentation ###
for i, uline in enumerate(u):
if i >= i and i < i+nLines:
mklist.append(uline)
j=j+1
现在的问题是,我无法附加到 mklist,因为它是一个字符串:
AttributeError: 'str' object has no attribute 'append'
如何在该循环中分配这些值?
最佳答案
您可以使用更合适的集合,例如字典:
nLines = 10
nrepeats = 2
j=0
i=0
my_dict = {}
while (j<nrepeats):
### Generating empty lists ###
my_dict[str(j)] = []
### do the segmentation ###
for i, uline in enumerate(u):
if i >= i and i < i+nLines:
my_dict[str(j)].append(uline)
j=j+1
关于python - 如何生成许多列表并为其赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42675507/