weixin_39017744
weixin_39017744
2019-10-22 22:49
采纳率: 71.1%
浏览 1.9k

请问python中如何删除二维列表中值全部为指定数的一列?

二维列表list=
[[0,0,0,0,0,0,1,0]
[1,1,0,1,0,1,1,1]
[0,0,0,1,0,0,1,0]
[1,0,0,0,0,0,1,1]
[1,1,0,1,0,1,1,1]
[1,1,0,1,0,0,1,1]
[1,0,0,0,0,1,1,0]
[0,0,0,0,0,0,0,0]]
其中第三和第五列全部都是0了,则删除这两列。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • qq_39412061
    吃鸡王者 2019-10-23 15:21
    已采纳

    建议:变量名尽量不要和关键字或内部函数相同,你用list当变量名很容易出问题
    import numpy as py
    arr=np.array([[0,0,0,0,0,0,1,0]
    ,[1,1,0,1,0,1,1,1]
    ,[0,0,0,1,0,0,1,0]
    ,[1,0,0,0,0,0,1,1]
    ,[1,1,0,1,0,1,1,1]
    ,[1,1,0,1,0,0,1,1]
    ,[1,0,0,0,0,1,1,0]
    ,[0,0,0,0,0,0,0,0]])
    arr=arr[:,arr.sum(0)>0]
    print(arr)

    点赞 评论
  • zz00217
    空白如空 2019-10-23 10:01
    # coding:UTF-8
    arrays = [[0,0,0,0,0,0,1,0]
    ,[1,1,0,1,0,1,1,1]
    ,[0,0,0,1,0,0,1,0]
    ,[1,0,0,0,0,0,1,1]
    ,[1,1,0,1,0,1,1,1]
    ,[1,1,0,1,0,0,1,1]
    ,[1,0,0,0,0,1,1,0]
    ,[0,0,0,0,0,0,0,0]]
    
    #获取多少列
    length = len(arrays[0])
    flag_list = list()
    
    for index in range(0, length):
        flag = True
        for array in arrays:
            if array[index] != 0:
                flag = False
                break;
        if flag:
            # 记录全为O的列
            print index
            flag_list.append(index)
    
    # 删除全为0的列
    for array in arrays:
        i = 0  # 因为pop一个长度会变换,记录位置改变
        for flag_index in flag_list:
            array.pop(flag_index-i)
            i += 1
        new_arrays.append(array)
    print arrays
    
    点赞 评论

相关推荐