Python - 连接最大元组
给定一个包含字符串及其大小的元组列表,任务是编写一个Python程序来连接所有具有最大大小的字符串。
例子:
Input : test_list = [(“Gfg is best”, 8), (“gfg is good”, 7), (“for”, 2), (“for all geeks”, 8)]
Output : “Gfg is best for all geeks”
Explanation : 8 is maximum tuple element and concatenation of keys yield the result.
Input : test_list = [(“Gfg is best”, 7), (“gfg is good”, 8), (“for”, 2), (“for all geeks”, 8)]
Output : “gfg is good for all geeks”
Explanation : 8 is maximum tuple element and concatenation of keys yield the result.
方法 #1:使用max() + itemgetter() +列表理解+ join()
在此,我们使用 max() 执行获取最大数量级数的任务,itemgetter 处理要查询的索引。字符串在使用列表理解匹配后由 join() 连接。
Python3
# Python3 code to demonstrate working of
# Concatenate Maximum Tuples
# Using max() + itemgetter() + list comprehension + join()
from operator import itemgetter
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
("for", 2), ("for all geeks", 8)]
# printing original list
print("The original list is : " + str(test_list))
# getting maximum
max_ele = max(test_list, key=itemgetter(1))[1]
# joining maximum
res = ' '.join([key for key, ele in test_list if ele == max_ele])
# printing result
print("The maximum concatenated strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Concatenate Maximum Tuples
# Using filter() + max() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
("for", 2), ("for all geeks", 8)]
# printing original list
print("The original list is : " + str(test_list))
# getting maximum
max_ele = max(test_list, key=itemgetter(1))[1]
# joining maximum
# filter checks for maximum values and concats
res = " ".join([ele[0]
for ele in filter(lambda ele: ele[1] == max_ele, test_list)])
# printing result
print("The maximum concatenated strings : " + str(res))
输出:
The original list is : [(‘Gfg is best’, 8), (‘gfg is good’, 7), (‘for’, 2), (‘for all geeks’, 8)]
The maximum concatenated strings : Gfg is best for all geeks
方法 #2:使用filter() + max() + itemgetter()
在这里,我们使用 filter() 而不是列表理解来执行过滤任务。其余的所有功能类似于所有方法。
蟒蛇3
# Python3 code to demonstrate working of
# Concatenate Maximum Tuples
# Using filter() + max() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
("for", 2), ("for all geeks", 8)]
# printing original list
print("The original list is : " + str(test_list))
# getting maximum
max_ele = max(test_list, key=itemgetter(1))[1]
# joining maximum
# filter checks for maximum values and concats
res = " ".join([ele[0]
for ele in filter(lambda ele: ele[1] == max_ele, test_list)])
# printing result
print("The maximum concatenated strings : " + str(res))
输出:
The original list is : [(‘Gfg is best’, 8), (‘gfg is good’, 7), (‘for’, 2), (‘for all geeks’, 8)]
The maximum concatenated strings : Gfg is best for all geeks