作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我将数据存储在列表中,例如
images = ['pdf-one','gif-two','jpg-three']
如何在连字符处将它们拆分为多个元素 - 而不是子列表。即
images = ['pdf','-one','gif','-two','jpg','-three']
不是
images = [['pdf','-one'],['gif','-two'],['jpg','-three']]
最佳答案
在这种情况下,使用正则表达式进行拆分可以得到最易读的代码:
import re
hyphensplit = re.compile('(-[a-z]+)').split
images = [part for img in images for part in hyphensplit(img) if part]
演示:
>>> import re
>>> hyphensplit = re.compile('(-[a-z]+)').split
>>> images = ['pdf-one','gif-two','jpg-three']
>>> [part for img in images for part in hyphensplit(img) if part]
['pdf', '-one', 'gif', '-two', 'jpg', '-three']
关于python - 如何将列表元素分成两部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21644883/
我是一名优秀的程序员,十分优秀!