关于拆分(Python函数)

关于拆分(Python函数),python,function,split,Python,Function,Split,我的问题是关于分裂函数 我有一个元组: 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'] 我怎么能这么做呢?你的问题很无效,但是 这对你有用吗: names = 'test_1_1', 'test_1_2', 'test_1_3-4-5'

我的问题是关于分裂函数

我有一个元组:

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']

我怎么能这么做呢?

你的问题很无效,但是

这对你有用吗:

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']

假设您的
字符串
确实是一个
元组
,您可以使用:

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']

您好,欢迎光临:请注意,您的变量似乎是一个元组,您的输出根本无效。你的问题没有道理,谢谢!这就是我需要的