[英]How to build tuple array variable of integers + strings in python for loop?
Manually built variable STAFFLIST works in django database as a list of choices listed as PositiveSmallIntegerField.手动构建的变量 STAFFLIST 在 django 数据库中工作,作为列为 PositiveSmallIntegerField 的选项列表。
STAFF1 = 1
STAFF2 = 2
STAFF3 = 3
STAFFLIST = (
(STAFF1, _('John Doe')),
(STAFF2, _('Lisa Beauty')),
(STAFF3, _('Harry Potter')),
)
Print for this variable works as follows:打印此变量的工作方式如下:
>>>print(STAFFLIST[1])
(2, 'Lisa Beauty')
>>> print(STAFFLIST[1][0])
2
>>> print(STAFFLIST[1][1])
Lisa Beauty
>>>
How to built this variable automatically in for loop based on the actual list of staffs?如何根据实际人员列表在for循环中自动构建此变量? I was trying something like below, but unsuccsessful:
我正在尝试类似下面的操作,但没有成功:
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
staff = User.objects.filter(is_staff=True)
idx=0
for stf in staff:
STAFFLIST[idx] = (stf.id, _(stf.first_name + ' ' + stf.last_name))
idx=idx+1
I am getting error like:我收到如下错误:
TypeError: 'str' object does not support item assignment
I believe, my problem is low knowledge level of python datatypes.我相信,我的问题是 python 数据类型的知识水平低。 And currently, I am trying to work with tuple datatype and to store string inside.
目前,我正在尝试使用元组数据类型并将字符串存储在其中。
I have solved the for loop problem.我已经解决了for循环问题。 Folowing code works and builds the same tuple array as the manually defined variable:
以下代码工作并构建与手动定义的变量相同的元组数组:
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
staff = User.objects.filter(is_staff=True)
idx=0
for stf in staff:
if idx == 0:
STAFFLIST = ((stf.id, _(stf.first_name + ' ' + stf.last_name)),)
idx=1
else:
STAFFLIST = STAFFLIST + ((stf.id, _(stf.first_name + ' ' + stf.last_name)),)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.