list中的字符串去除空格,我被搞晕了

lioujian47 2008-09-21 06:32:53


请教一个问题,我搞了半天也没搞出来:(
st = [['a b', 'c d', 'e f'], ['hj kj df gfgf']]
要把st改成如下模样,即去掉每个字符串的空格:
st = [['ab', 'cd', 'ef'], ['hjkjdfgfgf']]

其实这样就可以输出,但接下来怎么弄也没对:(
for i in st:
for j in i:
j.replace(' ','')
我曾想再建立一个list来保存,但也没弄好:(

比如这样:
>>> ts = []
>>> for i in st:
for j in i:
ts.append(j.replace(' ',''))
>>> ts
['ab', 'cd', 'ef', 'hjkjdfgfgf']

而如果这样:
>>> ts = []
>>> n = 0
>>> for i in st:
ts.append([])
for j in i:
ts[n].extend(j.replace(' ',''))
n += 1

>>> ts
[['a', 'b', 'c', 'd', 'e', 'f'], ['h', 'j', 'k', 'j', 'd', 'f', 'g', 'f', 'g', 'f']]
这是怎么回事啊?我越弄越糊涂了:(

比较前一个例:为什么结果不是[['a', 'b', 'c', 'd', 'e', 'f', 'h', 'j', 'k', 'j', 'd', 'f', 'g', 'f', 'g', 'f']



没法了...
...全文
2202 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
iambic 2008-09-21
  • 打赏
  • 举报
回复
st = [['a b', 'c       d', 'e          f'], ['hj kj  df     gfgf']]
print [ [s.replace(' ', '') for s in x] for x in st]
lioujian47 2008-09-21
  • 打赏
  • 举报
回复
谢谢你的详细说明:)
iambic 2008-09-21
  • 打赏
  • 举报
回复
关于我的代码可以Google: python list comprehension
简单的示例:
>>> x = [1, 2, 3]
>>> [i + 1 for i in x]
[2, 3, 4]


你原来的代码我改了下:
st = [['a b', 'c       d', 'e          f'], ['hj kj  df     gfgf']]

ts = []
n = 0
for i in st:
ts.append([])
for j in i:
print j.replace(' ', '')
#ts[n].extend(j.replace(' ',''))
ts[n].append(j.replace(' ',''))
n += 1

print ts

也就是说,用append把一个东西加到list中;而extend是把一个东西打破,再一个个加到list。
lioujian47 2008-09-21
  • 打赏
  • 举报
回复
谢谢,可惜没有讲述道理:(

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧