Python: 在多维列表中添加项目

Python: add item in multidimensional list

嗨,我对 python 不是很了解。我想将数字插入到多维数组 (c) 中,数字之间的最大差异为 0.21%。但是,我想将彼此相差.21的数字的其他相关数字放入同一个数组中。

nums = sorted([47255, 47343, 47865, 47904, 48000, 48001], reverse=True)

i = 0
b = 1

c = []

while i < len(nums):
    while b < len(nums) - i:
        a = ((nums[i] - nums[i+b]) / nums[i+b]) * 100
        if a < 0.21:
            if (nums[i] in x for x in c):
                c.append([])
                c[i].append(str(nums[i]))
                c[i].append(str(nums[i + b]))
            else:
                c.append(str(nums[i]))
                c.append(str(nums[i + b]))
                c.append([])
        b = b + 1
    b = 1
    i = i + 1
print(c)

结果:

[['48001', '48000', '48001', '47904'], ['48000', '47904'], ['47904', '47865'], [], ['47343', '47255']]

我想要什么

[['48001', '48000', '47904', '47865'], ['47343', '47255']]

(48001 48000 max difference %0.21 but more difference %0.21 48001 between 47865) but 47865 .21 47904 .21 48000 and this too max .21 48001 所有这些数字都必须在 c 数组的索引 1 中。

47343 不是最大差异 .21 47865 那么这也应该在第二个索引中。

47343 最大 %0.21 差异 47255

c = [['48001', '48000', '47904', '47865'], ['47343', '47255']]

img please look 对不起我的英语不好。

希望我答对了问题,我有一个解决方案。
算法很简单-在矩阵中添加新元素时:

  • 测试每个现有数组的每个元素是否满足新数字的 (0.21%) 条件
    • 如果是,将新数字添加到该数组
    • 如果该数字未添加到任何数组(没有现有数字满足条件),则创建一个仅包含新数字的新数组

code00.py

#!/usr/bin/env python

import sys


def add_to_array(n, arr2d, ratio=0.0021):
    for arr in arr2d:
        for elem in arr:
            if abs(n - elem) / max(n, elem) <= ratio:
                arr.append(n)
                return
    arr2d.append([n])


def main(*argv):
    nums = sorted([47255, 47343, 47865, 47904, 48000, 48001], reverse=True)
    c = []
    for n in nums:
        add_to_array(n, c)
    print("The matrix:", c)


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q066411225]> "e:\Work\Dev\VEnvs\py_pc064_03.08.07_test0\Scripts\python.exe" code00.py
Python 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)] 64bit on win32

The matrix: [[48001, 48000, 47904, 47865], [47343, 47255]]

Done.