Python|元组列表中的选择性值选择
有时,在使用元组列表时,我们会遇到一个问题,即我们有一个特定的键列表,我们只需要元组列表中这些键的值。这在对特定实体进行评级或求和方面具有实用性。让我们讨论一些可以做到这一点的方法。
方法 #1:使用dict() + get()
+ 列表理解
我们可以通过首先将列表转换为字典然后使用列表推导来使用 get函数获取特定键的值来执行此特定任务。
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using dict() + get() + list comprehension
# 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
# Selective Value selection in list of tuples
temp = dict(test_list)
res = [temp.get(i, 0) for i in select_list]
# printing result
print ("The selective values 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 of keys : [1, 3]
方法 #2:使用next()
+ 列表推导
这个特定问题可以使用下一个函数来解决,该函数使用迭代器执行迭代,因此可以更有效地实现可能的解决方案。
# Python3 code to demonstrate
# Selective Value selection in list of tuples
# using next() + list comprehension
# 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
# Selective Value selection in list of tuples
res = [next((sub[1] for sub in test_list
if sub[0] == i), 0) for i in select_list]
# printing result
print ("The selective values 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 of keys : [1, 3]