python for循环在项目之间添加逗号

时间:2011-01-21 04:37:53

标签: python django for-loop

我想在列表中循环添加项之间的逗号。必须有一种更简单的方法来编写它,这样它就可以一次性抽出所有标签,而不必反复循环。

for top_item in items.get_top_tags():
    tag1 = top_item.item.get_name(0)
for top_item in items.get_top_tags(1):
    tag2 = top_item.item.get_name()
for top_item in items.get_top_tags(2):
    tag3 = top_item.item.get_name()
for top_item in items.get_top_tags(3):
    tag4 = top_item.item.get_name()
for top_item in items.get_top_tags(4):
    tag5 = top_item.item.get_name()

tags = (tag1 + ',' + tag2 + ',' + tag3 + ',' + tag4 + ',' + tag5

3 个答案:

答案 0 :(得分:2)

似乎items.get_top_tags()会返回一个包含单个项目的列表?如果是这样,试试这个:

# 'n' is the number of tags you'll be returning, I suppose
', '.join(items.get_top_tags(i)[0].get_name() for i in range(n))

答案 1 :(得分:1)

我不确定你试图在你的例子的第一部分做什么,但我怀疑你可以用以下的东西替换它:

tag_items = items.get_top_tags(4)

这可能会给你一些标签项的集合(例如列表或元组)。

然后,您可以执行list comprehension以获取仅标记名称的列表:

tag_names = [tag.item.get_name() for tag in tag_items]

最后,您可以使用str.join方法将名称列表转换为逗号分隔的字符串。以下是其使用示例:

tags = ','.join([tag1, tag2, tag3, tag4, tag5)

答案 2 :(得分:0)

尝试类似','.join(yourList)

的内容