如何删除额外的','在元组中的django(python) [英] How to remove extra ',' in tuple in django(python)

查看:122
本文介绍了如何删除额外的','在元组中的django(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用django构建一个id列表有一个问题。如果我选择多于1个id,那么如果我只选择一个,它会在列表中产生额外的'''。

  testa = tuple([k ['id'] for k in queryset.values('id')])
print testa

如果在查询中具有正确的1个id,它将显示

 (1234,)

除此之外

 (1234,1244)

如何删除额外的'

解决方案

 (1234,)
/ pre>

是1元组的正确Python表示形式。 (1234)将错误,因为它被认为是数学括号中的简单整数,评估为 1234 ,而不是包含它的元组。



这是不同的列表,因为方括号没有这个双重目的也意味着数学的操作顺序,所以虽然 [1234] [1234,] 都是长度为1的列表的有效表示,默认文本表示可以是没有额外的逗号。



如果您正在设计一个不需要与Python相同的元组的您自己的文本表示形式,则可以执行eg.:

 '(%s)'%','.join(map(repr,testa))


I have one problem in building a list of id using django. if i choose more than 1 id it ok but if i choose only one it will produce extra ',' in list.

testa = tuple([k['id'] for k in queryset.values('id')])
print testa

if in the queryset have exactly 1 id, it will display

(1234,)

other than that it ok

(1234,1244)

How can i remove extra ', in list'

解决方案

(1234,)

is the correct Python representation of a 1-tuple. (1234) would be wrong as that is taken as a simple integer in mathematical parentheses, evaluating to 1234, not a tuple containing it.

This is different for lists because the square brackets don't have this double purpose of also meaning mathemtical order-of-operations, so whilst [1234] and [1234,] are both valid representations of a length-1-list, the default textual representation can be without the extra comma.

If you are devising your own textual representation of a tuple that does not need to be the same as Python's, you could do eg.:

'(%s)' % ', '.join(map(repr, testa))

这篇关于如何删除额外的','在元组中的django(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆