j=0
x=[]
for j in range(9):
x=x+ [j]
this will output
[1,2,3,4,5,6,7,8,9]
i wanted it as开发者_StackOverflow中文版
['1','2','3'...
how can I get it?
convert to string:
>>> [str(i) for i in range(9)]
['0', '1', '2', '3', '4', '5', '6', '7', '8']
if you want your list to start with 1
just change your range
function:
>>> [str(i) for i in range(1, 9)]
['1', '2', '3', '4', '5', '6', '7', '8']
Also, you don't need to initialise loop variable (j=0
is not required).
Python 2
>>> map(str, range(1, 9))
['1', '2', '3', '4', '5', '6', '7', '8']
Python 3
>>> list(map(str, range(1, 9)))
['1', '2', '3', '4', '5', '6', '7', '8']
Documentation for range
:
- http://docs.python.org/library/functions.html#range
Ok, the "good" python ways are already posted, but I want to show you how you would modify your example to make it work the way you want it:
j=0
x=[]
for j in range(9):
x = x + [str(j)]
j=0
x=[]
for j in range(9):
x=x+[str(j)]
精彩评论