python-3.x 接受列表中的多个元素

xnifntxz  于 2023-03-20  发布在  Python
关注(0)|答案(2)|浏览(135)

我想从列表中输入多个元素,并让程序打印出准确的“pointCount”数量。如果我从任何一个列表中输入一个元素,它都可以工作(例如,“a”= 1点,“f”= 3点)。问题是,如果我,例如,输入“cafe”之类的东西,程序只会打印出“0点”而不是“7点”。

onePointLetters = ["a", "b", "c"]
twoPointLetters = ["d", "e"]
threePointLetter = ["f"]
enterLetter = input("Enter a letter: ").lower()
while enterLetter != "stop":
    pointCount = 0
    if enterLetter in onePointLetters:
        pointCount += 1
    if enterLetter in twoPointLetters:
        pointCount += 2
    if enterLetter in threePointLetter:
        pointCount += 3
    print("You have a total of " + str(pointCount) + " points!")
    enterLetter = input("Enter another letter: ").lower()

我尝试了另一种编码方案。

onePointLetters = ["a", "b", "c"]
twoPointLetters = ["d", "e"]
threePointLetter = ["f"]
enterLetter = input("Enter a letter: ").lower()
while enterLetter != "stop":
    pointCount = 0
    for onePointLetters in enterLetter:
        pointCount += 1
    for twoPointLetters in enterLetter:
        pointCount += 2
    for threePointLetter in enterLetter:
        pointCount += 3
    print("You have a total of " + str(pointCount) + " points!")
    enterLetter = input("Enter another letter: ").lower()

如果我保留其中一个for循环,后者似乎可以正常工作,但如果保留所有三个for循环,程序只会将所有值相加,每输入一个字母就得到6分(d = 6分,afe = 18分)。
有没有更好的解决办法?

rpppsulh

rpppsulh1#

您的第一个代码可以工作,但是您应该在while循环之外初始化pointCount
我建议用字典来解释这个问题:

letterPoints = {"a":1, "b":1, "c":1, "d":2, "e":2, "f":3}
pointCount   = 0
while True:
    enterLetter  = input("Enter a letter: ").lower()
    if enterLetter == "stop": break
    pointCount  += letterPoints.get(enterLetter,0)
    print("You have a total of", pointCount, "points!")
z2acfund

z2acfund2#

您的第一次编码尝试检查输入是否在pointlist中。“a”在列表中,因此是1个点。“f”也在列表中,因此是3个点。但是,“Cafe”不在任何列表中。
您需要找到一种方法来遍历input-word的每个字母,并检查它们应该向pointsCounter添加多少点数。

onePointLetters = ["a", "b", "c"]
twoPointLetters = ["d", "e"] 
threePointLetters = ["f"]
enterWord = input("Enter a letter: ").lower()

while enterWord != "stop":
    pointCount = 0

    # Loop through every letter of the word entered
    for letter in enterWord:
        # Adds points to pointCount according to the pointsystem
        if letter in onePointLetters:
            pointCount += 1
        elif letter in twoPointLetters:
            pointCount += 2
        elif letter in threePointLetters:
            pointCount += 3
    print("You have a total of " + str(pointCount) + " 
    points!")
    enterWord = input("Enter another letter: ").lower()

相关问题