python合并字符串数组,如何使用List Comprehension将Python中的2D数组合并为一个字符串?...

List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.

Say, I have a 2D list:

li = [[0,1,2],[3,4,5],[6,7,8]]

I would like to merge this either into one long list

li2 = [0,1,2,3,4,5,6,7,8]

or into a string with separators:

s = "0,1,2,3,4,5,6,7,8"

Really, I'd like to know how to do both.

解决方案

Like so:

[ item for innerlist in outerlist for item in innerlist ]

Turning that directly into a string with separators:

','.join(str(item) for innerlist in outerlist for item in innerlist)

Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:

for innerlist in outerlist:

for item in innerlist:

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值