【问题标题】:About split (Python function)关于拆分(Python函数)
【发布时间】:2020-04-26 15:02:45
【问题描述】:

我的问题是关于拆分功能的

我有一个元组:

name = 'test_1_1', 'test_1_2', 'test_1_3-4-5'...

我想得到这样的东西:

['test_1_1', 'test_1_2', 'test_1_3', 'test_1_4', 'test_1_5']

我该怎么做?

【问题讨论】:

标签: python function split


【解决方案1】:

您的问题非常无效,但是,

这对你有用吗:

names = 'test_1_1', 'test_1_2', 'test_1_3-4-5'                                        

res = [] 
for name in names: 
    if '-' not in name: 
        res.append(name) 
        continue 
    parts = name.split('_') 
    for sub in parts[2].split('-'): 
        res.append(f'{parts[0]}_{parts[1]}_{sub}') # This is what makes sense to me but maybe you want the following: 
        # res.append(f'{parts[0]},{parts[1]},{sub}')



print(res)

输出:

['test_1_1', 'test_1_2', 'test_1_3', 'test_1_4', 'test_1_5']

【讨论】:

  • 谢谢!这就是我需要的
【解决方案2】:

假设你的string确实是tuple,你可以使用:

import re

name = 'test_1_1', 'test_1_2', 'test_1_3-4-5'
new_name = [re.split(r"[_-]", x) for x in name]
# [['test', '1', '1'], ['test', '1', '2'], ['test', '1', '3', '4', '5']]

或者,由于我没有完全理解您的问题,您可能需要:

new_name = [re.sub(r"[_-]", ",", x) for x in name ]
# ['test,1,1', 'test,1,2', 'test,1,3,4,5']

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多