Python 相关问题

2017-09-11 18:28:59 +08:00
 MrgHOST

‘ 7w876543217w'怎么拆分成[7w,87,65,43,21,7w]

list['7w876543217w']貌似不行

2535 次点击
所在节点    Python
12 条回复
Cooky
2017-09-11 18:35:33 +08:00
[ list[i,I+2] for i in range(len(list)) ]
Cooky
2017-09-11 18:36:08 +08:00
@Cooky 第一个逗号改冒号,切片
MrgHOST
2017-09-11 18:37:03 +08:00
@Cooky 谢谢
qlbr
2017-09-11 18:37:46 +08:00
>>> import re
>>> string='7w876543217w'
>>> re.findall('.{2}',string)
['7w', '87', '65', '43', '21', '7w']
Cooky
2017-09-11 18:41:17 +08:00
@MrgHOST 直接用 str 切片就行,转 list 多余了…
nauynah
2017-09-11 20:10:54 +08:00
>>> [str[i: i+2] for i in range(0, 10, 2)]
acheapskate
2017-09-11 20:11:19 +08:00
s = '7w876543217w'
l = [m + n for m,n in zip(s[0::2],s[1::2])]
acheapskate
2017-09-11 20:19:32 +08:00
@nauynah range(0, 11, 2) ,不然截取不到最后 2 个字符 。感觉用 range 分隔还是最明晰方便的
nauynah
2017-09-11 20:35:59 +08:00
@acheapskate 是的,我把字符串长度看成 10 了
40huo
2017-09-11 21:30:47 +08:00
[string[x : x + width] for x in range(0, len(string), width)]
yucongo
2017-09-13 00:32:28 +08:00
In [538]: [elm + s[1::2][idx] for idx, elm in enumerate(s[::2])]
Out[538]: ['7w', '87', '65', '43', '21', '7w']
yucongo
2017-09-13 00:41:14 +08:00
In [544]: s
Out[544]: '7w876543217w'

In [545]: [ s[2*idx: 2*idx+2] for idx in range(len(s)//2)]
Out[545]: ['7w', '87', '65', '43', '21', '7w']

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/389833

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX