1

i have a list such as this 1,2,3,4,5,6,7,8,9,10. I want to loop through it with python code, and properly format it to 1,2,3,4,5,6,7,8,9,10. The following is the code that i am using to execute the loop

lst = [1,2,3,4,5,6,7,8,9,10]
for x in lst:
    print "%s,"%x

This is the return value 1,2,3,4,5,6,7,8,9,10,

Can python pick up the last element of the loop and change the format of the loop?

4

4 回答 4

4

您可以使用join,但您需要将ints 更改为字符串:

print ','.join(str(x) for x in lst)
于 2013-06-07T19:06:30.493 回答
1

您可以指定分隔符并加入列表:

print ", ".join(str(x) for x in lst)

另外,我建议不要隐藏内置名称list,而是将您的号码称为其他名称。

于 2013-06-07T19:05:11.330 回答
0

纯娱乐:

>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> str(lst)[1:-1]
'1, 2, 3, 4, 5, 6, 7, 8, 9, 10'
于 2013-06-07T19:12:37.250 回答
0

如果要显式循环遍历它,而不是打印空格:

import sys
my_list = range(1,10+1) 
for x in my_list:
    sys.stdout.write("%s," % x)

或者

>>> my_list = range(1,10+1) 
>>> print ','.join(map(str, my_list)) + ','

最后一个+ ','必须在最后有一个逗号。

这个词list是python中的内置词,所以你应该避免命名变量list,因为这会从命名空间中删除关键字。

>>> a = (1,2,3)
>>> print a
(1, 2, 3)
>>> print list(a)
[1, 2, 3]
>>> type(a) == list
False
>>> type(list(a)) == list
True
于 2013-06-07T19:06:14.817 回答