python - 在 python 中使用 2D 列表的优雅方式

标签 python python-2.7 numpy

我刚刚开始使用 Python 2.7 几个月。我通常在 Python 中处理一些 2D 列表,这是一个简单的任务,但我想知道是否有一些更优雅的方法可以在 Python 2.7 中完成同样的工作?

这是我的任务。我有一个二维列表:

my_list = [["__cat_1", "__cat_2"],
           ["__cat_3", "__cat_4"]]

我想将上面的 2D 字符串列表转换为 2D 整数列表。

expected_result = [[1, 2], [3, 4]]

像往常一样,我执行以下操作:

def convert_2D_string_list(my_list):
    for a_group in my_list:
        yield [int(k.replace("__cat_","")) for k in a_group]

但是当我的输入有 3 个维度时,上述方法无法工作,例如:

my_second_list = [[["__cat_1", "__cat_2"], "__cat_12"],
                  [["__cat_3", "__cat_4"], "__cat_34"]]

如果我的输入列表是整数,我知道转换它的优雅方法。例如:

def convert_2D_int_list:
    my_list = [[1, 2], [3, 4]]
    import numpy as np
    # Assume that, I want to add 1 for each of element

    # Convert to numpy array
    my_list = np.asarray(my_list)
    my_list += 1

    # my_list = [[2, 3], [4, 5]]
    return my_list

我的 convert_2D_string_list 方法的最佳实践是什么? 因此,如果它不是 2D 列表,而是 3D 列表 -> 我不会担心维数。

如有任何建议,我们将不胜感激。 谢谢。

最佳答案

Numpy 数组对于数字来说工作得很好,对于字符串来说有点棘手。 np.vectorize是针对这种情况的解决方法,即使没有进行任何性能改进。但它可以管理任意数量的维度,希望您会发现它很优雅。

a=np.array([[[['__cat_0', '__cat_1'],
         ['__cat_2', '__cat_3']],

        [['__cat_4', '__cat_5'],
         ['__cat_6', '__cat_7']]],


       [[['__cat_8', '__cat_9'],
         ['__cat_10', '__cat_11']],

        [['__cat_12', '__cat_13'],
         ['__cat_14', '__cat_15']]]])


def f(str): return int(str[6:])        
fv=np.vectorize(f)

print(fv(a))

给出:

[[[[ 0  1]
   [ 2  3]]

  [[ 4  5]
   [ 6  7]]]


 [[[ 8  9]
   [10 11]]

  [[12 13]
   [14 15]]]]    

备注:anp.vectorize(lambda n : '__cat_'+str(n))(np.arange(16).reshape((2,)*4) ) ;)

关于python - 在 python 中使用 2D 列表的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47089645/

相关文章:

python - 如何在覆盖 pandas 数据框中潜在重复项的同时重命名列

python - 提取数值

python - 如何找到阈值内最长的子数组?

python - 在 Flask 中创建 webhook

python - 使用 Python 连接到 JIRA API 时 SSL3 证书验证失败

python - 如何在 Windows 上最大化窗口并禁用调整大小而不覆盖任务栏 - tkinter/tk-toolkit

python - 在 if 语句中为 1 到 50 之间的任何数字制作通配符整数

python - 用从索引到另一个的值填充 numpy 矩阵

python - 使用 python 的网络服务器

python - 使用 Python 解析 shell 文件输出