在Python中比较两个可变长度的元组

时间:2017-06-15 15:16:31

标签: python numpy tuples

我有两个元组元组,我想根据它们的第一个元素比较值

list1 = ((1, 2450.0), (2, 2095.0), (4, 1290.0), (5, 1190.0), (6, 1150.0), (7, 1150.0), (8, 1090.0), (9, 1090.0))
list2 = ((1, 2673.0), (4, 1488.0), (5, 1139.0), (6, 1057.0), (7, 1482.0), (8, 1037.0), (9, 1169.0), (10, 937.0))

预期结果应为

list1 = ((1, 2450.0), (2, 2095.0), (3, nan),(4, 1290.0), (5, 1190.0), (6, 1150.0), (7, 1150.0), (8, 1090.0), (9, 1090.0), (10,nan))
list2 = ((1, 2673.0), (3, nan),(4, 1488.0), (5, 1139.0), (6, 1057.0), (7, 1482.0), (8, 1037.0), (9, 1169.0), (10, 937.0))

这样做的有效方法是什么?

1 个答案:

答案 0 :(得分:0)

如果我正确地理解了你的问题,你想检查每个元组是否包含存储在每个子元组的第一个元素中的某些数字,如果数字不在里面,则创建一个子元组,第二个元素等于无(如果nan表示无)。

我会遵循这个过程,这可能不是最有效的。

# Create first a list which contains the desired numbers to be checked
checkTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 )

# Create a function to check if each number is in one of the sub-tuples
def chooseName( checkTuple, randomList ):
    newList = []
    for checkItem in checkTuple:
        itemFound = False
        for item in randomList:
            if checkItem in item:
                numberFound = True
                break
        if numberFound:
            newList.append( checkItem )
        else:
            newList.append( (checkItem, None) )
    return tuple( newList )

# Call the function and take back the tuple
newList1 = chooseName( checkTuple, list1 )