如何从('a', 'b', 'c')获取('a','a/b','a/b/c')?

4

我应该如何从这个结构出发呢?

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

7
你目前尝试过什么?你只需要这些作为字符串吗?如果是,作为一个提示,可以看一下字符串格式化。 - Paritosh Singh
6个回答

12
你可以使用 itertools.accumulate():
from itertools import accumulate
l = ['a', 'b', 'c']
print(list(accumulate(l, '{}/{}'.format)))

这将输出:

['a', 'a/b', 'a/b/c']

2
这应该可以工作:

最初的回答:

l = ['a', 'b', 'c']
new_list =[]
for i in range(len(l)):
    new_list.append("/".join([a for a in l[:i+1]]))

2

您可以使用简单的列表推导来实现这一点。

l = ['a', 'b', 'c']
['/'.join(l[:i]) for i in range(1, len(l)+1)]
# ['a', 'a/b', 'a/b/c']

如果性能很重要,你可以自己实现accumulate: "累加"。
out = [l[0]]
for l_ in l[1:]:
    out.append('{}/{}'.format(out[-1], l_))

out
# ['a', 'a/b', 'a/b/c']

对于给定的问题,这种方法比itertools稍微快一些。

最初的回答:


1
如果你必须使用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))]

我更喜欢内置的join函数:

output =  ['/'.join(input[:n + 1]) for n in range(0, len(input))]

1
您可以使用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']

0
一个递归解决方案:
思路很简单,我们使用分治法。如果我们知道前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', 'a/b', 'a/b/c']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接