如何使用python在嵌套列表中拆分具有特定字符的字符串?

如何使用python在嵌套列表中拆分具有特定字符的字符串?,python,string,split,nested-lists,Python,String,Split,Nested Lists,我有一个带有一些字符串的嵌套列表。我想以奇数间隔拆分带有“-”字符的字符串,如我的结果所示。我见过。但这帮不了我 mylist= [['1 - 2 - 3 - 4 - 5 - 6'],['1 - 2 - 3 - 4']] myresult = [[['1 - 2'] , ['3 - 4'] , ['5 - 6']],[['1 - 2] ,[ 3 - 4']]] 试试这个: res = [] for x in mylist: data = list(map(str.strip, x[0

我有一个带有一些字符串的嵌套列表。我想以奇数间隔拆分带有“-”字符的字符串,如我的结果所示。我见过。但这帮不了我

mylist= [['1 - 2 - 3 - 4 - 5 - 6'],['1 - 2 - 3 - 4']]

myresult = [[['1 - 2'] , ['3 - 4'] , ['5 - 6']],[['1 - 2] ,[ 3 - 4']]]
试试这个:

res = []
for x in mylist:
    data = list(map(str.strip, x[0].split('-')))
    res.append([[' - '.join(data[y * 2: (y + 1) * 2])] for y in range(0, len(data) // 2)])
print(res)
输出:

[[['1 - 2'], ['3 - 4'], ['5 - 6']], [['1 - 2'], ['3 - 4']]]
试试这个:

res = []
for x in mylist:
    data = list(map(str.strip, x[0].split('-')))
    res.append([[' - '.join(data[y * 2: (y + 1) * 2])] for y in range(0, len(data) // 2)])
print(res)
输出:

[[['1 - 2'], ['3 - 4'], ['5 - 6']], [['1 - 2'], ['3 - 4']]]

如果您喜欢单线解决方案,请看这里

res = [[[s] for s in map(' - '.join,
                         map(lambda x: map(str, x),
                             zip(x[::2], x[1::2])))]
       for lst in mylist for x in (lst[0].split(' - '),)]

如果您喜欢单线解决方案,请看这里

res = [[[s] for s in map(' - '.join,
                         map(lambda x: map(str, x),
                             zip(x[::2], x[1::2])))]
       for lst in mylist for x in (lst[0].split(' - '),)]
列表理解:

[[[" - ".join(item)] for item in zip(*[iter(sub.split(" - "))]*2)] for l in mylist for sub in l]
列表理解中是否有一些更改:

[[[" - ".join(item)] for item in zip(*[iter(sub.split(" - "))]*2)] for l in mylist for sub in l]

有一些无用的空格,你应该删除它们,因为OP不想看到它们。谢谢@deadshot@RiccardoBucco谢谢你的信息。我已经更新了我的答案有一些无用的空间,你应该删除它们,因为OP不想看到它们。谢谢@deadshot@RiccardoBucco谢谢你的信息。我已经更新了我的答案