Python – 记录中的配对存在
有时,在处理Python记录时,我们可能会遇到需要检查记录中是否存在配对的问题,或者如果一个不存在,另一个也不应该存在。这种问题在数据科学和 Web 开发等领域很常见。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [(‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘good’)]
pairs = (‘is’, ‘good’)
Output : [(‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘good’)]
Input :
test_list = [(‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘better’)]
pairs = (‘better’, ‘good’)
Output : []
方法#1:使用生成器表达式
这是可以执行此任务的蛮力方式。在此,我们检查两个数字的存在/不存在,如果不存在或两者都存在,则接受结果。
Python3
# Python3 code to demonstrate working of
# Paired Existence in Records
# Using generator expression
# initializing list
test_list = [('Gfg', 'is', 'Best'),
('Gfg', 'is', 'good'),
('CS', 'is', 'good')]
# printing original list
print("The original list is : " + str(test_list))
# initializing Pairs
pairs = ('Gfg', 'Best')
# Paired Existence in Records
# Using generator expression
res = []
for sub in test_list:
if ((pairs[0] in sub and pairs[1] in sub) or (
pairs[0] not in sub and pairs[1] not in sub)):
res.append(sub)
# printing result
print("The resultant records : " + str(res))
Python3
# Python3 code to demonstrate working of
# Paired Existence in Records
# Using XNOR
# initializing list
test_list = [('Gfg', 'is', 'Best'),
('Gfg', 'is', 'good'),
('CS', 'is', 'good')]
# printing original list
print("The original list is : " + str(test_list))
# initializing Pairs
pairs = ('Gfg', 'Best')
# Paired Existence in Records
# Using XNOR
res = []
for sub in test_list:
if (not ((pairs[0] in sub) ^ (pairs[1] in sub))):
res.append(sub)
# printing result
print("The resultant records : " + str(res))
原始列表是:[('Gfg', 'is', 'Best'), ('Gfg', 'is', 'good'), ('CS', 'is', 'good')]
结果记录:[('Gfg', 'is', 'Best'), ('CS', 'is', 'good')]
方法 #2:使用 XNOR
这是解决此问题的另一种方法。在此,使用 XOR运算符的功能来执行此任务并对结果取反。
Python3
# Python3 code to demonstrate working of
# Paired Existence in Records
# Using XNOR
# initializing list
test_list = [('Gfg', 'is', 'Best'),
('Gfg', 'is', 'good'),
('CS', 'is', 'good')]
# printing original list
print("The original list is : " + str(test_list))
# initializing Pairs
pairs = ('Gfg', 'Best')
# Paired Existence in Records
# Using XNOR
res = []
for sub in test_list:
if (not ((pairs[0] in sub) ^ (pairs[1] in sub))):
res.append(sub)
# printing result
print("The resultant records : " + str(res))
The original list is : [('Gfg', 'is', 'Best'), ('Gfg', 'is', 'good'), ('CS', 'is', 'good')]
The resultant records : [('Gfg', 'is', 'Best'), ('CS', 'is', 'good')]