简体   繁体   English

有人可以向我解释这个奇怪的 Python for loop 吗?

[英]Could someone explain me this strange Python for loop?

I was occupied on a project and I found a code that was perfectly what I was searching for, but there are parts that I don't understand could some of you explain me it please?我忙于一个项目,我找到了一个完全符合我要求的代码,但是有些部分我不明白,你们中的一些人可以解释一下吗? This is the code that I found:这是我找到的代码:

from pynput import keyboard
from pynput.keyboard import Controller

keypress = Controller()

COMBINATIONS = [
    {keyboard.KeyCode(char='a'), keyboard.KeyCode(char='z')},
]

current = set()

def execute():
    for loop in range(0, 10):
        keypress.press('w')
        keypress.release('w')

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]): # THIS PART
        current.add(key)
        print(current)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS): #THIS PART
           execute()

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]): #THIS PART
        current.remove(key)

    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

I commented the parts that I don't understand with #THIS PART commend Thanks for helping:)我用#THIS PART表扬评论了我不理解的部分 感谢您的帮助:)

The answer to this question can be divided into two parts:这个问题的答案可以分为两部分:

1. List Comprehension: 1.列表理解:

First, list comprehension: which is a way to write a for loop in just one line.首先,列表理解:这是一种在一行中编写for循环的方法。 So, instead of writing:所以,而不是写:

result = []
for COMBO in COMBINATIONS:
    result.append(key in COMBO)

You can write it in one line like so:你可以像这样写成一行:

result = [key in COMBO for COMBO in COMBINATIONS]

As you can see, result is a list of boolean values... either True or False .如您所见, result是 boolean 值的列表...... TrueFalse Which brings the second part;这带来了第二部分;

2. any() function 2.任何() function

The second part is the function any() .第二部分是 function any() This function returns True if one of the given items in True .如果True True And False if non of the given items is True .如果没有给定的项目是True ,则为False


So, the answer to your question is that this part:所以,你的问题的答案是这部分:

any([key in COMBO for COMBO in COMBINATIONS])

It checks if the key exists in any of COMBO of the given COMBINATION .它检查key是否存在于给定COMBINATION的任何COMBO中。

Hope this answers your question!希望这能回答你的问题!

I understood better when I tried to apply it in a easy code.当我尝试在简单的代码中应用它时,我理解得更好。 Thanks for your great explanation:)感谢您的精彩解释:)

import os
Passwords = ["abcd", "efgh"]
inpt = input()


for List in Passwords:
    if (inpt in List) == True:
        print("Correct password! : True!")
        os.startfile('Chrome.exe')


if any([inpt in List for List in Passwords]):
    print("Correct password! : True!")
    os.startfile('Chrome.exe')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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