[英]Splitting a string into a list in python
我有一長串字符,我想將其拆分為單個字符列表。 我想將空格也包括在列表的成員中。 我該怎么做呢?
你可以做:
list('foo')
空格將被視為列表成員(雖然沒有組合在一起,但你沒有指定你需要的)
>>> list('foo')
['f', 'o', 'o']
>>> list('f oo')
['f', ' ', 'o', 'o']
這里有一些關於字符串和字符串列表的比較,以及另一種在字符串中明確表示字符串的方法,以便在現實生活中使用list():
b='foo of zoo'
a= [c for c in b]
a[0] = 'b'
print 'Item assignment to list and join:',''.join(a)
try:
b[0] = 'b'
except TypeError:
print 'Not mutable string, need to slice:'
b= 'b'+b[1:]
print b
這不是原始問題的答案,而是上述評論中的“我如何使用dict選項”(模擬2D數組):
WIDTH = 5
HEIGHT = 5
# a dict to be used as a 2D array:
grid = {}
# initialize the grid to spaces
for x in range(WIDTH):
for y in range(HEIGHT):
grid[ (x,y) ] = ' '
# drop a few Xs
grid[ (1,1) ] = 'X'
grid[ (3,2) ] = 'X'
grid[ (0,4) ] = 'X'
# iterate over the grid in raster order
for x in range(WIDTH):
for y in range(HEIGHT):
if grid[ (x,y) ] == 'X':
print "X found at %d,%d"%(x,y)
# iterate over the grid in arbitrary order, but once per cell
count = 0
for coord,contents in grid.iteritems():
if contents == 'X':
count += 1
print "found %d Xs"%(count)
元組是不可變的,可以制作完美的字典鍵。 在分配給它們之前,網格中的單元格不存在,因此對於稀疏數組來說它非常有效,如果這是你的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.