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

を使用できますが、 s を文字列joinに変更する必要があります。int

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

スペースを出力せずに明示的にループしたい場合:

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 に答える