如何删除多余的“,”在 django(python) 的元组中
我在使用 django 构建 id 列表时遇到一个问题。如果我选择 1 个以上的 id 就可以了,但如果我只选择一个,它会在列表中产生额外的“,”。
testa = tuple([k['id'] for k in queryset.values('id')])
print testa
如果查询集中恰好有 1 个 id,它将显示
(1234,)
除此之外的其他内容
(1234,1244)
我如何删除多余的“,在列表中”
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是 1 元组的正确 Python 表示形式。
(1234)
是错误的,因为它被视为数学括号中的简单整数,计算结果为1234
,而不是包含它的元组。这对于列表来说是不同的,因为方括号没有这种双重目的,也意味着数学运算顺序,所以虽然
[1234]
和[1234,]
都是 length-1-list 的有效表示,默认文本表示可以不带额外的逗号。如果您正在设计自己的元组文本表示形式,并且不需要与 Python 的相同,您可以这样做:
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 to1234
, 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.:
要编写包含单个值的元组,即使只有一个值,也必须包含逗号。
您可以索引元组以获得所需的输出:
To write a tuple containing a single value you have to include a comma, even though there is only one value.
You can index the tuple to get the desired output:
实际上你不必这样做。冒号就在元组的字符串表示形式中。例如,您可以通过以下方式创建自己的字符串
actually you don't have to. the colon sign is just there in a string representation of the tuple. For example you can just create your own string by
这就是 python 显示具有单个值的元组的方式,另请注意,创建具有单个值的元组的推荐语法也是 x = (1,) ,这有助于区分元组和函数调用。
如果你真的想要像你描述的那样的输出,你可以尝试
thats' how python displays the tuples with single values , also note that the recommended syntax for creating a tuple with single value is also
x = (1,)
that helps in differentiating a tuple from a function call .If you really want an output like you describe you can try
你说你想要一个列表,但事实上你正在创建一个元组。
要获取 id 列表,请查看
values_list
Yo say you want a list but de facto you are creating a tuple.
To get a list of ids take a look at
values_list
在 python 3 中:
然后格式化你的 SQL:
In python 3:
Then format your SQL: