Python 如何从(';a';、';a/b';、';a/b/c';)中获取(';a';、';b';、';c')?
我怎样才能摆脱这种结构Python 如何从(';a';、';a/b';、';a/b/c';)中获取(';a';、';b';、';c')?,python,Python,我怎样才能摆脱这种结构 >>> input = ['a', 'b', 'c'] 对这个 >>> output ['a', 'a/b', 'a/b/c'] 以优雅(实用)的方式 现在我有这个: >>> from functools import reduce >>> res = [] >>> for i in range(len(input)): ... res.append(reduce(la
>>> input = ['a', 'b', 'c']
对这个
>>> output
['a', 'a/b', 'a/b/c']
以优雅(实用)的方式
现在我有这个:
>>> from functools import reduce
>>> res = []
>>> for i in range(len(input)):
... res.append(reduce(lambda a, b: a + '/' + b, input[:i+1]))
...
>>> res
['a', 'a/b', 'a/b/c']
您可以使用:
这将产生:
['a', 'a/b', 'a/b/c']
这应该起作用:
l = ['a', 'b', 'c']
new_list =[]
for i in range(len(l)):
new_list.append("/".join([a for a in l[:i+1]]))
您可以使用简单的列表理解来实现这一点
l = ['a', 'b', 'c']
['/'.join(l[:i]) for i in range(1, len(l)+1)]
# ['a', 'a/b', 'a/b/c']
如果性能很重要,您可以推出自己的
累积实现:
out = [l[0]]
for l_ in l[1:]:
out.append('{}/{}'.format(out[-1], l_))
out
# ['a', 'a/b', 'a/b/c']
对于给定的问题,这比itertools快一点。如果必须使用reduce,可以这样做:
from functools import reduce
input = ['a', 'b', 'c']
output = [reduce(lambda a, b: f"{a}/{b}", input[:n + 1]) for n in range(0, len(input))]
我更喜欢内置的连接功能:
output = ['/'.join(input[:n + 1]) for n in range(0, len(input))]
您可以使用count
按步骤分割字符串:
from itertools import count
input = ['a', 'b', 'c']
s = '/'.join(input)
c = count(1, 2)
[s[:next(c)] for _ in input]
# ['a', 'a/b', 'a/b/c']
递归解决方案:
这个想法很简单,我们使用分而治之的方法。
如果我们知道第一个n-1字符串(或字符)的答案,这个问题就可以解决。在这种情况下,我们需要做的就是收集一个字符串中的所有字符,并用“/”分隔它们(在这种情况下是“a/b/c”)
我们传递一个空列表作为第二个参数来存储结果
input = ['a', 'b', 'c']
def foo(list1, list2):
if (len(list1) == 0):
return list2
else:
s = list1[0]
for char in list1[1:]:
s += '/' + char
list2.insert(0, str)
return foo(list1[:-1], list2)
>foo(输入,[])
到目前为止你试过什么?你需要这些线吗?如果是这样,作为提示,请看一下字符串格式。
input = ['a', 'b', 'c']
def foo(list1, list2):
if (len(list1) == 0):
return list2
else:
s = list1[0]
for char in list1[1:]:
s += '/' + char
list2.insert(0, str)
return foo(list1[:-1], list2)
['a', 'a/b', 'a/b/c']