控制嵌套列表/字符串上的递归 - python

假设我有以下输入:

items = [1, 2, [3, 4], (5, 6), 'ciao', range(3), (i for i in range(3, 6))]

我想对items执行一些递归操作。

为了简单起见,假设我要展平商品(但可以是其他任何东西),一种方法是:

def flatten(items, shallow=(str, bytes, bytearray)):
    for item in items:
        if isinstance(item, shallow):
            yield item
        else:
            try:
                yield from flatten(item)
            except TypeError:
                yield item

这将产生:

print(list(flatten(items)))
[1, 2, 3, 4, 5, 6, 'ciao', 0, 1, 2, 3, 4, 5]

现在如何修改flatten(),以便产生以下内容(对于任意嵌套级别)?

print(list(flatten(items)))
[1, 2, 3, 4, 5, 6, 'c', 'i', 'a', 'o', 0, 1, 2, 3, 4, 5]

python大神给出的解决方案

只需在浅层检查旁边添加一个长度检查:

if isinstance(item, shallow) and len(item) == 1: 

如何在Matplotlib条形图后面绘制网格线 - python

x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=…

子条件的python条件覆盖 - python

我试图找到一个python代码覆盖率工具,该工具可以衡量语句中是否包含子表达式:例如,我想看看下面的示例是否涵盖了condition1 / condition2 / condtion3?if condition1 or condition2 or condition3: x = true_value python大神给出的解决方案 对此的唯一合理答案是:当前…

USB设备发行 - python

我目前正在使用PyUSB。由于我不熟悉USB,所以我不知道如何执行以下操作。我已经从Python PyUSB成功连接到我的USB设备硬件。在代码中,我需要重置USB设备硬件。通过向硬件发送命令来完成。现在,在硬件重置后,我想从Python PyUSB释放当前的USB设备。然后,我想在重置后将其重新连接到USB设备硬件。请让我知道,如何释放USB设备连接和接口…

Python-熊猫描述了抛出错误:无法散列的类型“ dict” - python

更新:我正在使用“ Socrata开源API”中的一些示例代码。我在代码中注意到以下注释:# First 2000 results, returned as JSON from API / converted to Python # list of dictionaries by sodapy. 我不熟悉JSON。我已经下载了一个数据集,并创建了一个包含大量…

在Pytorch中重复张量的特定列 - python

我有一个大小为X的pytorch张量m x n和一个长度为num_repeats的非负整数n列表(假定sum(num_repeats)> 0)。在forward()方法中,我想创建一个大小为X_dup的张量m x sum(num_repeats),其中i的列X重复num_repeats[i]次。张量X_dup将在forward()方法的下游使用,因此需…