【问题标题】:Obtain the column of a matrix that is composed by tuples获取由元组组成的矩阵的列
【发布时间】:2020-11-16 12:05:01
【问题描述】:

我有点困惑如何到达元组索引并将它们分组到一个元组中。我的函数接收一个 3x3 矩阵、我的 tab 和一个对应于矩阵列索引的整数。

【问题讨论】:

  • 真正的初学者级问题,抱歉,SO 不是来解决家庭作业问题的,请告诉我们你解决这个特定问题的方法。
  • 我想知道关于引发ValueError 异常的部分是否是您要求的基本部分……如果我尝试使用n=4 接受的答案,如您的规范中所述,那么我会收到一个不同的错误留言"IndexError: tuple index out of range"

标签: python python-3.x tuples


【解决方案1】:

不知道是什么阻碍了你,这与索引列表列表相同:

def obtain_column(tab, c):
    return tuple(row[c] for row in tab)
    # take element at position c in each row, and make a tuple


tab = ((1,-1,0),
       (1,0,-1),
       (1,-1,0))

print(obtain_column(tab, 0))
print(obtain_column(tab, 1))
print(obtain_column(tab, 2))

列的输出:

(1, 1, 1)
(-1, 0, -1)
(0, -1, 0)

【讨论】:

  • 感谢您的回答和时间!它对我帮助很大!实际上,这是一个简单的方法。对矩阵的行做同样的事情。
  • 酷,不客气。对于行,您可以直接使用tab[r]获取整行
【解决方案2】:

你可以这样做:

ret = ()

for row in tab:
    ret += (row[c],)  # the , is for adding the integer as a tuple element.

return ret

请注意,上面的代码假设每个元组在索引 c 中都有一个元素。你可能需要添加一些东西来检查,这取决于你的完整程序。

【讨论】:

  • 参考 Reblochon Masque 的回答,它更“python-y”。这是一个创建新元组的过程的演示,而不是使用单线。
【解决方案3】:

你想做的事都可以做

  1. 使用众所周知的成语zip(*iterable) 转置元组的元组,以获得tab 的列作为zip 对象的元素,
  2. 然后在 列表理解中,我们从 1 开始计算列对象,并丢弃所有计数不匹配的列n
  3. 如果列计数匹配,则列表col 的唯一元素是由zip(*tab) 生成的与请求列对应的元组
  4. 如果col 不是空列表,我们可以返回其唯一元素——请求的列作为元组
  5. 否则没有匹配的列计数ncol 是空列表,我们没有return,因此我们必须根据您的规范提出ValueError

所以

In [35]: def obtain_column(t, n):
    ...:     col = [c for i, c in enumerate(zip(*tab), 1) if i==n]
    ...:     if col : return col[0]
    ...:     raise ValueError('obtain_column: invalid argument %d.'%n)
    ...: for i in (1,2,4): print(obtain_column(tab, i))
(1, 1, 1)
(-1, 0, -1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-1c03f33aa1cf> in <module>
      3     if col : return col[0]
      4     raise ValueError('obtain_column: invalid argument %d.'%n)
----> 5 for i in (1,2,4): print(obtain_column(tab, i))

<ipython-input-35-1c03f33aa1cf> in obtain_column(t, n)
      2     col = [c for i, c in enumerate(zip(*tab), 1) if i==n]
      3     if col : return col[0]
----> 4     raise ValueError('obtain_column: invalid argument %d.'%n)
      5 for i in (1,2,4): print(obtain_column(tab, i))

ValueError: obtain_column: invalid argument 4.

In [36]:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 2019-12-08
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多