微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试将列表中仅包含一个 int 的列表转换为列表中的一个 int

如何解决尝试将列表中仅包含一个 int 的列表转换为列表中的一个 int

我有一个列表,其中包含整数和列表中的整数列表。

我正在尝试创建一种方法来检查列表中是否有任何 1 个数字列表,并将该数字列表转换为一个 int。所以它不再是列表中的列表。

我使用以下代码作为指导,但此代码适用于矩阵,而我的是 3d 列表。

nmap x :r /path/to/file<CR>

这就是我想要做的,但我得到了 indexerror: invalid index to scalar variable:

# Process grid with Possible array values as cells are solved
for row in range(0,GRIDSIZE):
   for col in range(0,GRIDSIZE):
      # Found correct cell value = Only 1 possible value
      if np.size(P[row,col]) == 1:
         singleton = P[row][col][0]
         grid[row][col] = singleton
         # Remove from Possible list
         P[row,col].remove(singleton)

对于“从可能的列表中删除”部分,是否有一个简单的 pythonic 命令可以从二维列表删除该单例元素?

这是目前列表的样子:

    for row in range(0,9):
        for col in range(0,9):
                    if np.size((values[row][col])) == 1:
                        singleton = values[row][col][0]
                        values[row][col] = singleton

解决方法

您可以使用嵌套列表理解:

original_list = [[[7],8,5,[6],1,3,[2,6],[4],9],[6,4,[8,2,7,5],[[1],[1,6]],6,9,1],[9,[1],[7],3],[3,[9],[6]],[5,2],[4,7],[7]],4]]

new_list = [[elem[0] if (isinstance(elem,list) and len(elem)==1) else elem for elem in sublist] for sublist in original_list ]

# new_list
"""
[[7,4]]"""

编辑:使用 for 循环:

new_list = []
for sublist in original_list:
    new_sublist = []
    for elem in sublist:
        if (isinstance(elem,list) and len(elem) == 1):
            new_sublist.append(elem[0])
        else:
            new_sublist.append(elem)
    new_list.append(new_sublist)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?