python - 如何从 ('a' , 'a/b' , 'a/b/c' , ('a' ) 得到 'b' , 'c' , 0x104567910 )?

标签 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(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']

关于python - 如何从 ('a' , 'a/b' , 'a/b/c' , ('a' ) 得到 'b' , 'c' , 0x104567910 )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814893/

相关文章:

python - 有没有办法在多行代码中添加注释?

python - 如何访问 Google Colab 笔记本上的文件

Python:固定等待接收套接字数据的时间

python - 当 x 轴为日期时,如何在 matplotlib 中的 xticks(使用 x 坐标)下方绘制文本?

python - 使用字典从列表中获取键和值

python - boto3 站点包 S3Response 语法在collectstatic上出错

python - 返回非零退出状态 3 python2.7 子进程 check_output

python - Python 中 import 和 __import__ 的区别

python - 为 matplotlib 图分配随机颜色

python - cx_Oracle 未安装在 Oracle Linux 上