【问题标题】:Adding django id to a list将 django id 添加到列表中
【发布时间】:2016-04-16 06:59:39
【问题描述】:

我正在尝试将 django id 存储到列表中。但它将两位数存储为单独的两位数。例如,它将 10 存储为 1 和 0。它将值存储为 unicode 字符。谁能帮帮我

   def practice_view(request, id=None):
        msg = ''
        if request.method == 'POST':
            questions = request.POST.get('Que');
            list = [];
            result = [];
            total = 0;
            for i in questions:
                if i.isdigit():
                    list.append(i)
                total = total + 1;
    During debugging this is what it displays
    Que=u'[6, 7, 8, 9, 10, 11, 12]'
    questions=u'[6, 7, 8, 9, 10, 11, 12]'
    list=[u'6', u'7', u'8', u'9', u'1', u'0', u'1', u'1', u'1', u'2']

【问题讨论】:

  • 1.避免使用列表作为变量名。 2.在追加到列表之前将字符串转换为int。
  • 尝试questions = request.POST.getlist('Que') 而不是request.POST.get。这仅适用于您在帖子数据中发送多个名称为 Que 的值。

标签: python django list unicode


【解决方案1】:

像这样改变你的代码,

import ast
def practice_view(request, id=None):
    msg = ''
    if request.method == 'POST':
        questions = ast.literal_eval(request.POST.get('Que'))
        lst = [];
        result = [];
        total = 0;
        for i in questions:
            if type(i) == 'int':
                lst.append(i)
            total = total + 1;

由于查询字符串参数Que 的值是一个字符串,python 应该遍历字符串中存在的每个字符。

【讨论】:

  • 感谢您的回答。试过了。但它仍然是一样的。在列表中存储时,2 位数字存储为单独的两位数字。例如。 10 作为 1 和 0。
  • print questions 的输出是什么?
  • 问题包含 [1,2,3,4,5,6,7,8,9,10,11,12] 但当它附加到列表时,它被存储为 [1,2 ,3,4,5,6,7,8,9,1,0,1,1,1,2]
  • 发布type(questions)的输出
猜你喜欢
  • 2016-09-12
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多