简体   繁体   中英

Sorting and comparing lists with a nested for loop

Im Trying to sort and compare lists with a for loop, but I keep getting the error:

sorted(lista[str(y+1)])
KeyError: '14454'

Here's my code:

l = 0
k = 0
u = 0
lista = {}


sys.stdout = open("1.txt", "w")
for i in range(1,28):
    for j in range(1,28):
        for k in range(1,28):
          a = float(i)
          b = float(j)
          c = float(k)
          q = (a*b*c) / ((a+b+c)*(a+b+c)*(a+b+c))
          if q > (1 / 81) and q < 1:
            if a != b and b != c and c != a:
              lista[str(l)] = [a,b,c]
              l = l + 1

for x in range(l):
    for y in range(l):
        sorted(lista[str(x)])
        sorted(lista[str(y+1)])

        if lista[str(x)] == [str(y+1)]:
            u = u + 1
    
sys.stdout.close()

The Error (Explained)

KeyError: "14454"

means that that the key is non-existent. For example, if my dict is {"hi": "hi", "hello": "hello"} , and I try calling myDict["hiya"] , it will return KeyError: "hiya" .

What should you do?

Well, debug it. By placing print(lista) before the loop (to avoid the console being overflowed), you can see the keys of lista and find your code solution from there!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM