简体   繁体   English

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

[英]Elegant way to work with 2D list in python

I have just start with Python 2.7 for few months. 我刚开始使用Python 2.7已有几个月了。 I usually work with some 2D list in Python, simple task but I wonder that is there some more elegant way to do the same my job in Python 2.7? 我通常使用Python处理一些2D列表,但任务很简单,但我想知道是否有一些更优雅的方法可以在Python 2.7中完成同样的工作?

Here is my task. 这是我的任务。 I have a 2D list: 我有一个二维列表:

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

I want to convert the above 2D string list to 2D integer list. 我想将上面的2D字符串列表转换为2D整数列表。

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

As usual, I do as the following: 和往常一样,我按以下步骤进行:

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

But the above could not work when my input has 3 dimensions like: 但是当我的输入具有以下3个维度时,上述方法不起作用:

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

If my input list is integer , I know the elegant way to convert for transform it. 如果我的输入列表是integer ,我知道一种转换转换的优雅方法。 For example: 例如:

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

What is the best practice for my convert_2D_string_list method? 我的convert_2D_string_list方法的最佳实践是什么? So in case of it is not 2D list, but 3D list -> I will not afraid about the number of dimensions. 因此,如果不是2D列表,而是3D列表->我将不担心尺寸数。

Any suggestion would be appreciated. 任何建议,将不胜感激。 Thank you. 谢谢。

Numpy array works very well with NUMbers, it's a little more tricky with strings. NumPy数组与NUMbers一起使用时效果很好,而字符串则比较棘手。 np.vectorize is a work around for such situation, even no performance improvement is done. np.vectorize可以解决这种情况,即使没有提高性能也是如此。 But it manages any number of dimensions, hope you will find it elegant. 但是它可以管理任意多个尺寸,希望您会发现它很优雅。

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))

gives : 给出:

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

  [[ 4  5]
   [ 6  7]]]


 [[[ 8  9]
   [10 11]]

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

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

Modify the values whilst recursively copying the list(s). 在递归复制列表的同时修改值。

def visit(fn, xs):
    return [visit(fn, x) if isinstance(x, list) else fn(x) for x in xs]

in this case the modification function fn is something like: 在这种情况下,修改函数fn类似于:

    def categorize(s):
        return int(re.match(r'__cat_(\d*)', s).group(1))

testing this: 测试此:

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

print visit(categorize, my_second_list)

outputs: 输出:

> [[[1, 2], 12], [[3, 4], 34]]

You can convert your string 2D list to int 2D list using map and list comprehensions 您可以使用地图和列表推导将字符串2D列表转换为int 2D列表

my_list = [["__cat_1", "__cat_2"],["__cat_3", "__cat_4"]]    
my_list = [map(lambda z: int(z.split('_')[-1]), ls) for ls in my_list]
print my_list # [[1,2],[3,4]]

3d list: 3D清单:

my_list = [["__cat_1", "__cat_2", '__cat_3'],["__cat_1", "__cat_2", '__cat_3']]
my_list = [map(lambda z: int(z.split('_')[-1]), ls) for ls in my_list]
print my_list # [[1,2,3],[1,2,3],[1,2,3]]

我希望这对您有用:

def con(x): # you can do here whatever u want return x.split('_')[-1] y= [con(v) for v in my_list]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM