我正在尝试比较字典键的长度,然后将最长的内容保存在变量中。
我正在这样做
num==9
问题是变量中存储了多个值 我们怎么解决呢?
答案 0 :(得分:0)
问题:比较字典键的长度...变量中最长的长度。
我认为您正在使用str
键
# Creat a dict with keys from a sentence
_dict = dict.fromkeys("Lorem Ipsum is simply dummy text of the printing and typesetting industry.".split(), None)
# Create a ordered list from the dict keys
_list = list(_dict.keys())
# Use the buildin index/max function to get the index of the max value
_max = _list.index(max(_list))
print("_list:{}\nmax:[{}] {}".format(_list, _max, _list[_max]))
输出:
_list:['of', 'the', 'simply', 'Lorem', 'is', 'and', 'typesetting', 'industry.', 'Ipsum', 'dummy', 'printing', 'text'] max:[6] typesetting
如果不想使用构建功能:
# Init start values
_max_key = None
_max = 0
# Loop the dict keys
for key in _dict.keys():
# Get the length of this key
_len = len(key)
# Condition: If this key length is greater than the previous
if _len > _max:
# Set _max to the current _len, for next Condition
_max = _len
# Save the key value
_max_key = key
print("max_key: {}".format(_max_key))
输出:
max_key: typesetting
使用Python测试:3.4.2