【问题标题】:Creating lists based on two conditions根据两个条件创建列表
【发布时间】:2017-06-04 19:42:13
【问题描述】:

我正在尝试根据用户数据创建列表。数据是 16 个问题的调查,因此我想将数据拆分为 16 个答案的列表,或者只是 answers = ['No data available] 的列表。到目前为止,我的代码如下所示。

studentanswers = []
contains_data = False
temp = []  
for i in answers:
if i == 'No data available':
    if contains_data:
        studentanswers.append(temp)
        temp = []
        studentanswers.append([i])
        contains_data = False
    else:
        studentanswers.append([i])
else:
    contains_data = True
    if len(temp) < 16:
        temp.append(i)
    else:
        studentanswers.append(temp)
        temp = []
        contains_data = False

但是,随着我的迭代,数据的计数不正确,并且一些数据被分配给了错误的用户。例如,学生 1 的第 16 题将变为学生 2 的第 1 题。

【问题讨论】:

  • 不清楚你在问什么。请分享示例输入和预期输出。

标签: python list python-3.x append


【解决方案1】:

尝试以下方法:

while answers:
    if answers[0] = 'No data available':
        studentanswers.append(['No data available'])
        answers = answers[1:]
    else:
       studentanswers.append(answers[:16])
       answers = answers[16:]

【讨论】:

  • 此方案仅在出现“无可用数据”时才划分数据。是否有办法在出现“无可用数据”时创建列表,并在列表中存在 16 个项目后创建列表?
  • 当没有出现“无可用数据”时,它也会创建一个列表。看看这一行 - studentanswers.append(answers[:16])
  • 我有一些错误,我清理了它们,这很好用,谢谢!
【解决方案2】:

你的问题不清楚,如果我没记错的话,你想要一个每个学生的答案列表。

如果是这种情况,那么这就足够了:

studentanswers = list()
for x in range(len(answers)/16):
    sudentsanswers.append(list(answers[y*16:(y+1)*16])

这假设每个学生都有 16 个答案。

编辑,我刚刚看到您的其他评论,这将起作用:

studentanswers = list()
studentanswers.append(list())
c = int(0)
for x in range(len(answers)):
    if (c<16 && x  != "No data available"):
        studentanswers[len(studentanswers)-1].append(x)
        c+=1
    else:
        c=0
        studentanswers.append(list())
        studentanswers[len(studentanswers)-1].append(x)
        if x == "No data available":
            studentanswers.append(list())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多