![](/img/trans.png)
[英]Python: How to sort an Array with with a combination of Strings and Integers
[英]How to build tuple array variable of integers + strings in python for loop?
手動構建的變量 STAFFLIST 在 django 數據庫中工作,作為列為 PositiveSmallIntegerField 的選項列表。
STAFF1 = 1
STAFF2 = 2
STAFF3 = 3
STAFFLIST = (
(STAFF1, _('John Doe')),
(STAFF2, _('Lisa Beauty')),
(STAFF3, _('Harry Potter')),
)
打印此變量的工作方式如下:
>>>print(STAFFLIST[1])
(2, 'Lisa Beauty')
>>> print(STAFFLIST[1][0])
2
>>> print(STAFFLIST[1][1])
Lisa Beauty
>>>
如何根據實際人員列表在for循環中自動構建此變量? 我正在嘗試類似下面的操作,但沒有成功:
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
我收到如下錯誤:
TypeError: 'str' object does not support item assignment
我相信,我的問題是 python 數據類型的知識水平低。 目前,我正在嘗試使用元組數據類型並將字符串存儲在其中。
我已經解決了for循環問題。 以下代碼工作並構建與手動定義的變量相同的元組數組:
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.