【问题标题】:Finding the max and min in a tuple of tuples在元组的元组中查找最大值和最小值
【发布时间】:2012-10-18 17:16:50
【问题描述】:

我是 python 新手,在查找元组元组的最小值和最大值时遇到了一些问题。我需要他们来规范我的数据。所以,基本上,我有一个由 13 个数字组成的列表,每个数字代表一些东西。每个数字在列表中构成一列,每列我需要maxmin。我尝试索引/迭代,但不断收到

的错误
max_j = max(j)

TypeError: 'float' object is not iterable

任何帮助将不胜感激!

代码是(假设 data_set_tup 是一个元组的元组,例如 ((1,3,4,5,6,7,...),(5,6,7,3,6,73,2. ..)...(3,4,5,6,3,2,2...)) 我还想使用标准化值创建一个新列表。

normal_list = []

for i in data_set_tup:

    for j in i[1:]: # first column doesn't need to be normalised
        max_j = max(j)
        min_j = min(j)
        normal_j = (j-min_j)/(max_j-min_j)
        normal_list.append(normal_j)
    normal_tup = tuple(normal_list)

【问题讨论】:

    标签: python tuples normalization


    【解决方案1】:

    您可以使用zip(*...) 将行转换为列,反之亦然。 (在 Python 3 中使用 list(zip(*...))

    cols = zip(*data_set_tup)
    normal_cols = [cols[0]] # first column doesn't need to be normalised
    for j in cols[1:]:
        max_j = max(j)
        min_j = min(j)
        normal_cols.append(tuple((k-min_j)/(max_j-min_j) for k in j)
    
    normal_list = zip(*normal_cols)
    

    【讨论】:

    • 这仍然给了我每行的最大值和最小值,而我需要每列的最大值和最小值(每个元组是一行,其中的值组成列,就像一个矩阵) .对于获取列的最大值和最小值有什么建议吗?
    【解决方案2】:

    这听起来确实像是非内置 numpy 模块的工作,或者可能是 pandas 模块,这取决于您的需要。

    添加对应用程序的额外依赖不应轻易完成,但如果您对类似矩阵的数据做了大量工作,那么如果您自始至终使用上述模块之一,您的代码可能会更快、更易读你的申请。

    我不建议将列表列表转换为 numpy 数组并再次返回以获得这个单一结果——最好使用 Jannes 答案的纯 python 方法。另外,鉴于您是 python 初学者,现在 numpy 可能有点矫枉过正。但我认为你的问题值得回答,指出这个一个选项。

    这是一个分步控制台说明,说明这将如何在 numpy 中工作:

    >>> import numpy as np
    >>> a = np.array([[1,3,4,5,6],[5,6,7,3,6],[3,4,5,6,3]], dtype=float)
    >>> a
    array([[ 1.,  3.,  4.,  5.,  6.],
           [ 5.,  6.,  7.,  3.,  6.],
           [ 3.,  4.,  5.,  6.,  3.]])
    >>> min = np.min(a, axis=0)
    >>> min
    array([1, 3, 4, 3, 3])
    >>> max = np.max(a, axis=0)
    >>> max
    array([5, 6, 7, 6, 6])
    >>> normalized = (a - min) / (max - min) 
    >>> normalized
    array([[ 0.        ,  0.        ,  0.        ,  0.66666667,  1.        ],
           [ 1.        ,  1.        ,  1.        ,  0.        ,  1.        ],
           [ 0.5       ,  0.33333333,  0.33333333,  1.        ,  0.        ]])
    

    所以在实际代码中:

    import numpy as np
    
    def normalize_by_column(a):
        min = np.min(a, axis=0)
        max = np.max(a, axis=0)
        return (a - min) / (max - min)
    

    【讨论】:

      【解决方案3】:

      我们有nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))。 首先,我们需要对其进行规范化。 Pythonic 方式:

      flat_tuple = [x for row in nested_tuple for x in row]
      

      输出:[1, 2, 3, 4, 5, 6, 7, 8, 9] # it's a list

      将其移至元组:tuple(flat_tuple),获取最大值:max(flat_tuple),获取最小值:min(flat_tuple)

      【讨论】:

        猜你喜欢
        • 2014-07-21
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-09
        • 2013-11-08
        相关资源
        最近更新 更多