Python 遍历 List, 拼接字符串

tim_spac 2008-01-28 06:37:10
Python遍历List我常用两种方式:
for item in thelist:
doSoming(item)

or
for i in range(len(thelist)):
doSoming(thelist[i])


第一种方式的应用变形:
strbuff = ''.join([someFunctionReturnString(item) for item in thelist])


第二种方式的变形应用涉及到另一个相关数组:
strbuff = ''
for i in range(len(thelist)):
if i<len(anotherList):
stuff += doSoming(thelist[i],anotherList[i])
else:
stuff += doSoming(thelist[i],'')


当涉及另一个相关数组时想用第一种方式表达该如何书写呢?
...全文
5037 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
levin108 2011-04-16
  • 打赏
  • 举报
回复
回复看一下~~~
maplele20 2008-09-10
  • 打赏
  • 举报
回复
mark
tim_spac 2008-01-28
  • 打赏
  • 举报
回复
thanks lot
亲密数 2008-01-28
  • 打赏
  • 举报
回复

ary1=[1,2,3,4,5]
ary2=[6,7,8,9,0,'a','b']
m=map(None,ary1,ary2)

for i,j in m:
print '(',i,',',j,')'



输出结果:
( 1 , 6 )
( 2 , 7 )
( 3 , 8 )
( 4 , 9 )
( 5 , 0 )
( None , a )
( None , b )

这应该是你想要的吧。
如果想元素数量以短的数组为准,可以用zip函数。

37,720

社区成员

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

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