簡體   English   中英

如何從('a','b','c')獲得('a','a / b','a / b / c')?

[英]How to get ('a', 'a/b', 'a/b/c') from ('a', 'b', 'c')?

我怎么能從這個結構出發

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

您可以使用itertools.accumulate()

from itertools import accumulate
l = ['a', 'b', 'c']
print(list(accumulate(l, '{}/{}'.format)))

這輸出:

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

如果性能很重要,您可以推出自己的accumulate實現:

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', 'a/b', 'a/b/c']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM