python - 如何生成许多列表并为其赋值

标签 python loops while-loop assign

我想从列表中读取特定数量的行并将所有这些值分配给一个新列表。然后我想从之前的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/

相关文章:

Python while - for 嵌套循环 对用户输入进行字符串搜索

python - Pandas 将函数应用于列

python - django 社交身份验证多帐户关联

jQuery - 数组元素上的迭代 + addClass

php - 如何在日期的第一天自动递增并从 1 重新开始?

c - while循环中变量变化的问题

java - 如何在这个 Java 程序中获取逻辑以使我的循环正常工作?

python - 如何在 R 中使用带有网状包的 Python 代码构建 lapply 风格的函数?

Python - 如何包装 np.ndarray 类?

python - 循环与异步定时器