Python迷宫3

2024-06-16 11:48:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图比较字典中键的长度,然后将最长键的内容保存在一个变量中。你知道吗

我就是这么做的

def path_mas_largo (labyrinth, idlaberinto):
    for i in range (len (labyrinth [idlaberinto]) - 1):
        if len (labyrinth [idlaberinto] [i] ['ensenanza' + str (i)]) > len (labyrinth [idlaberinto] [i + 1] ['ensenanza' + str (i + 1)]):
            j = len (labyrinth [idlaberinto] [i] ['ensenanza' + str (i)])
            if j > len (labyrinth [idlaberinto] [i + 1] ['ensenanza' + str (i + 1)]):
               camino_largo = laberinto [idlaberinto] [i] ['ensenanza' + str (i)]
               print (long_path)
               emular_recorrido (camino_largo, ventana, blanco, negro, celeste, aumento)

问题是变量中存储了多个值 我们怎么解决呢?你知道吗


Tags: pathin内容forlenif字典def
1条回答
网友
1楼 · 发布于 2024-06-16 11:48:35

Question: compare the length of the keys of a dictionary ... the longest in a variable.

我假设您正在使用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]))

Output:

_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))

Output:

max_key: typesetting

用Python:3.4.2测试

相关问题 更多 >