gpt4 book ai didi

python - 如何将列表元素分成两部分?

转载 作者:行者123 更新时间:2023-12-02 00:07:26 25 4
gpt4 key购买 nike

如果我将数据存储在列表中,例如

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com