Python – 键的最大字符串值长度
有时,在使用Python字典时,我们可能会遇到需要找到特定键的所有字符串值的最大长度的问题。此问题可能发生在日常编程和 Web 开发领域。让我们讨论可以执行此任务的某些方式。
例子 -
Input:
test_list = [{‘key1’ : “abcd”, ‘key2’ : 2}, {‘key1’ : “qwertyui”, ‘key2’ : 2}, {‘key1’ : “xcvz”, ‘key3’ : 3}, {‘key1’ : None, ‘key3’ : 4}]
Output: 8
Explanation: Among all values for given key key1
, qwertyui has maximum length (which is 8).
方法 #1:使用max() + len()
+ 列表理解
上述功能的组合可以用来解决这个问题。在此,我们使用 max() 和 len() 计算最大字符串长度。与每个的比较受列表理解的约束。
# Python3 code to demonstrate working of
# Maximum String value length of Key
# Using max() + len() + list comprehension
# initializing list
test_list = [{'Gfg' : "abcd", 'best' : 2},
{'Gfg' : "qwertyui", 'best' : 2},
{'Gfg' : "xcvz", 'good' : 3},
{'Gfg' : None, 'good' : 4}]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
filt_key = 'Gfg'
# Maximum String value length of Key
# Using max() + len() + list comprehension
temp = (sub[filt_key] for sub in test_list)
res = max(len(ele) for ele in temp if ele is not None)
# printing result
print("The maximum length key value : " + str(res))
The original list is : [{‘best’: 2, ‘Gfg’: ‘abcd’}, {‘best’: 2, ‘Gfg’: ‘qwertyui’}, {‘good’: 3, ‘Gfg’: ‘xcvz’}, {‘good’: 4, ‘Gfg’: None}]
The maximum length key value : 8
方法 #2:使用列表理解 + len() + max()
(一个班轮)
类似的任务也可以组合在一条线上执行,以实现紧凑的解决方案。
# Python3 code to demonstrate working of
# Maximum String value length of Key
# Using max() + len() + list comprehension (one liner)
# initializing list
test_list = [{'Gfg' : "abcd", 'best' : 2},
{'Gfg' : "qwertyui", 'best' : 2},
{'Gfg' : "xcvz", 'good' : 3},
{'Gfg' : None, 'good' : 4}]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
filt_key = 'Gfg'
# Maximum String value length of Key
# Using max() + len() + list comprehension (one liner)
res = len(max(test_list, key = lambda sub: len(sub[filt_key])
if sub[filt_key] is not None else 0)[filt_key])
# printing result
print("The maximum length key value : " + str(res))
The original list is : [{‘best’: 2, ‘Gfg’: ‘abcd’}, {‘best’: 2, ‘Gfg’: ‘qwertyui’}, {‘good’: 3, ‘Gfg’: ‘xcvz’}, {‘good’: 4, ‘Gfg’: None}]
The maximum length key value : 8