我想创建一个页面,其中包含用户列表和复选框,用于表示是否选择了用户,这将对选定的用户应用某些操作.我创建了一个表单类,如下所示:
#in forms.py
class UserSelectionForm(forms.Form):
"""form for selecting users"""
def __init__(self, userlist, *args, **kwargs):
self.custom_fields = userlist
super(forms.Form, self).__init__(*args, **kwargs)
for f in userlist:
self.fields[str(f.id)] = forms.BooleanField(initial=False)
def get_selected(self):
"""returns selected users"""
return filter(lambda u: self.fields[str(u.id)], self.custom_fields)
Run Code Online (Sandbox Code Playgroud)
在我的模板中,我在表中列出了用户,我希望此表的最后一列是那些复选框.我需要根据名称逐个渲染字段.我尝试创建一个模板标签,它将返回所需表单元素的html代码:
#in templatetags/user_list_tags.py
from django import template
register = template.Library()
#this is django template tag for user selection form
@register.filter
def user_select_field(form, userid):
"""
returns UserSelectionForm field for a user with userid
"""
key = std(userid)
if key not in form.fields.keys():
print 'Key …Run Code Online (Sandbox Code Playgroud) python django django-templates django-forms django-template-filters
问题与此处相同,但在 R 中。我有一个矩阵和一个向量,使得
length(vec) == nrow(mat)
Run Code Online (Sandbox Code Playgroud)
我如何获得这样的向量
v[i] == mat[v[i],i]
Run Code Online (Sandbox Code Playgroud)
我试图通过使用逻辑矩阵来实现这一点:
>a = matrix(runif(12),4,3)
a
[,1] [,2] [,3]
[1,] 0.6077585 0.5354680 0.2802681
[2,] 0.2596180 0.6358106 0.9336301
[3,] 0.5317069 0.4981082 0.8668405
[4,] 0.6150885 0.5164009 0.5797668
> sel = col(a) == c(1,3,2,1)
> sel
[,1] [,2] [,3]
[1,] TRUE FALSE FALSE
[2,] FALSE FALSE TRUE
[3,] FALSE TRUE FALSE
[4,] TRUE FALSE FALSE
> a[sel]
[1] 0.6077585 0.6150885 0.4981082 0.9336301
Run Code Online (Sandbox Code Playgroud)
它选择了正确的元素,但弄乱了顺序。我想使用mapply任何一个,但我不知道如何让它遍历行,就像在apply.
upd:@gsk3 建议使用as.list(as.data.frame(t(a)))这个作品。但我仍然想知道是否有更矢量化的方式,没有列表。