Python 3.6 字符串输入

Python 3.6 String input

我正在使用 Raspberry Pi 3 并使用 Python 控制三个 LED。 我可以说我很擅长Python。这是我的代码:

import RPi.GPIO as GPIO
import time

#GPIO Pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)

def led(color,state):
    if state == "on":
        if color == "g": #green
            GPIO.output(27,GPIO.HIGH)
        elif color == "y": #yellow
            GPIO.output(22,GPIO.HIGH)
        elif color == "r": #red
            GPIO.output(17,GPIO.HIGH)
        print ("LED on")
    elif state == "off":
        if color == "g":
            GPIO.output(27,GPIO.LOW)
        elif color == "y":
            GPIO.output(22,GPIO.LOW)
        elif color == "r":
            GPIO.output(17,GPIO.LOW)
        print ("LED off")

while True:
    leds_col = input("Color (r, g, y): ")
    leds_stat = input("On or Off: ")
    led(leds_col, leds_stat)

我有一个名为 led() 的函数,它有两个参数,color(g、y 或 r)和 state(开或关)。在 while 循环中,leds_col 询问控制台中的颜色,leds_stat 询问状态。 现在我想要实现的是将它们结合起来,而不是要求不同行中的颜色和另一行中的 LED 状态。所以例如我会在控制台上写:

g, on

它会打开绿色 LED。 我知道我可以使用 if 语句,例如: if led_input == "g, on": GPIO.output(27,GPIO.HIGH) 但我确信有更好的方法来做到这一点。

使用string.split():

while True: 
    what = input("Color [r,g,y] and state [on,off] (ex.: 'r on'): ").strip().lower().split()
    if len(what)==2:
        leds_col,leds_stat = what
        # sort the color input to reduce possible values
        leds_col = ''.join(sorted(leds_col))
        if leds_col not in "r g y gr ry gy gry" or leds_stat not in "on off":
            continue
    else:
        continue
    led(leds_col, leds_stat)

如果给出的输入无效,这将continue询问直到输入有效。 有关输入验证的更多想法,请参阅 Asking the user for input until they give a valid response


不相关 - 但您可以优化您的 led-函数:

def led(color,state):
    d = {"on":GPIO.HIGH, "off":GPIO.LOW,
         "g":27, "y":22, "r":17}

    for c in color:
        GPIO.output(d[c],d[state])
    print("LED",color,state)

通过使用查找字典:参见 dict()

这种方法可能会有所帮助。通过采用中间有 space 的两个输入。您可以根据 space 或任何其他字符拆分输入。然后它将颜色和状态放入两个不同的变量中。

>>> leds_col,leds_stat = input('Color(r,g,y) and State(on,off):').split(' ')
Color(r,g,y) and State(on,off):g on
>>> print(leds_col)
g
>>> print(leds_stat)
on
>>> 

或者,您也可以使用逗号或任何其他字符作为颜色和状态之间的分隔符。

str.split() 将能够将您的单行输入拆分为两个(或更多)变量:

>>> inp = input()
1,2
>>> inp
'1,2'
>>> a, b = inp.split(',')
>>> a
'1'
>>> b
'2'