Python – 选择性元组键的产物
有时,在使用元组列表时,我们会遇到一个问题,即我们有特定的键列表,我们只需要元组列表中这些键的值的乘积。这在特定实体的评级或产品中具有实用性。让我们讨论一些可以做到这一点的方法。
方法 #1:使用dict() + loop + get()
+ list comprehension
我们可以通过首先将列表转换为字典然后使用列表推导来使用 get函数获取特定键的值来执行此特定任务。使用循环执行值的乘积。
# Python3 code to demonstrate
# Product of Selective Tuple Keys
# using dict() + get() + list comprehension + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print ("The original list is : " + str(test_list))
# printing selection list
print ("The selection list is : " + str(select_list))
# using dict() + get() + list comprehension + loop
# Product of Selective Tuple Keys
temp = dict(test_list)
res = prod([temp.get(i, 0) for i in select_list])
# printing result
print ("The selective values product of keys : " + str(res))
输出 :
The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
方法 #2:使用next() + loop
+ 列表推导
这个特定问题可以使用下一个函数来解决,该函数使用迭代器执行迭代,因此可以更有效地实现可能的解决方案。使用循环执行值的乘积。
# Python3 code to demonstrate
# Product of Selective Tuple Keys
# using next() + list comprehension + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print ("The original list is : " + str(test_list))
# printing selection list
print ("The selection list is : " + str(select_list))
# using next() + list comprehension + loop
# Product of Selective Tuple Keys
res = prod([next((sub[1] for sub in test_list if sub[0] == i), 0) for i in select_list])
# printing result
print ("The selective values product of keys : " + str(res))
输出 :
The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3