遍历 Python 中的二维数组以获得不同的值

loop thru 2D-arrays in Python to get the different values

我有两个二维数组,它们的长度不同。

target = 
[('CRC_SRC', '2021-08-02 02:22:43.0'),
('CRC_RISK_LIB', '2021-08-02 02:22:42.0'),
('CRC_QST_LIB', '2021-08-02 02:22:42.0'),
('CRC_PROD_LIB', '2021-08-02 02:22:41.0'),
('CRC_TOOL_LIB', '2021-08-02 02:22:44.0'),
('CRC_MAP', '2021-07-26 02:31:56.0'),
('sample_table', '2021-07-31 02:31:56.0'),]

source = 
[('CRC_SRC', '2021-08-12 02:22:43.0'),
('CRC_RISK_LIB', '2021-08-02 02:22:42.0'),
('CRC_QST_LIB', '2021-08-12 02:22:42.0'),
('CRC_PROD_LIB', '2021-08-10 02:22:41.0'),
('CRC_TOOL_LIB', '2021-08-02 02:22:44.0'),
('CRC_DEFN_LV', '2021-07-26 02:31:56.0'),
('sample_table', '2021-07-25 02:31:56.0'),
('another table', '2021-07-29 03:31:56.0')]

我的目标是找到不同的和相同的值。我想出了一个嵌套循环来完成部分工作

for i in range(len(target)):
    for j in range(len(source)):
        if target[i] == source[j]:
            print('they are equal in name and timestamp: ', target[i])
        elif target[i][0] == source[j][0] and target[i][1] < source[j][1]:
            print('target timestamp is less than source timestamp: ', target[i], source[j])
        elif target[i][0] == source[j][0] and target[i][1] > source[j][1]:
            print('source timestamp is less than target timestamp: ', target[i], source[j])

输出为:

they are equal in name and timestamp:  ('CRC_RISK_LIB', '2021-08-02 02:22:42.0')
target timestamp is less than source timestamp:  ('CRC_QST_LIB', '2021-08-02 02:22:42.0') ('CRC_QST_LIB', '2021-08-12 02:22:42.0')
target timestamp is less than source timestamp:  ('CRC_PROD_LIB', '2021-08-02 02:22:41.0') ('CRC_PROD_LIB', '2021-08-10 02:22:41.0')
they are equal in name and timestamp:  ('CRC_TOOL_LIB', '2021-08-02 02:22:44.0')
source timestamp is less than target timestamp:  ('sample_table', '2021-07-31 02:31:56.0') ('sample_table', '2021-07-25 02:31:56.0')

所需的输出将添加以下内容:

source name is not in target name: ('CRC_DEFN_LV', '2021-07-26 02:31:56.0') ('another table', '2021-07-29 03:31:56.0')

如何在两个列表中找到不同的名称,而不考虑时间戳的差异?请指教,谢谢。我尝试了python中的set方法,比如-、|或 ^,但这不是我想要的。

这是一个您可以尝试的解决方案,

source_, target_ = dict(source), dict(target)

diff_ = " ".join(f"({i}, {source_[i]})" for i in source_.keys() - target_.keys())

print(
    "source name is not in target name:", diff_
)

source name is not in target name: (CRC_DEFN_LV, 2021-07-26 02:31:56.0) (CR_SRC, 2021-08-12 02:22:43.0) (another table, 2021-07-29 03:31:56.0)