【问题标题】:I'm make a program of a random string from a List and I ran to a problem. It ask the user to press p for previous string from the list我正在从一个列表中制作一个随机字符串的程序,但我遇到了一个问题。它要求用户按 p 获取列表中的上一个字符串
【发布时间】:2021-09-26 06:22:50
【问题描述】:

每按一次字母“p”都应该在列表中向后移动,显示上一个元素。如果当前显示的是第零个元素,则环绕显示最后一个元素。

import random

myList = ['A', 'B', 'C', 'D', 'E', 'F']
inList = print(random.choice(my_List))
while True:
    userQuest = input("Press 'p' for previous or 'n' for next ")
        if userQuest.lower == 'p':
            pre_num = my_list[my_list.index(inList) -1]

        else:
            print(done)

【问题讨论】:

  • 我遇到了一个问题好吧,有什么问题?
  • 我从列表中得到随机字母,当我按 p 从列表中获取前一个字母时,我得到一个错误。
  • 我们猜猜错误是什么?
  • 是的,我试着找出错误在哪里。
  • 你有堆栈跟踪。无论如何,当前代码甚至不会到达input,因为您使用的是my_Listmy_list,而变量名是myList。请提供minimal and reproducible Example

标签: python list loops random


【解决方案1】:

您的代码中有一些拼写错误。 此外,inList = print(random.choice(my_List)) 将始终返回一个NoneTypeinList,您可以通过type(inList) 进行检查。你应该把它改成inList = random.choice(my_List)

下面的代码应该适用于您的情况。

请注意会有一个极端情况:如果随机选择返回'A',则pre_num 将是'F'。请确保这是您所期望的结果。

import random

myList = ['A', 'B', 'C', 'D', 'E', 'F']
inList = random.choice(myList)
print(f'inList: {inList}')

while True:
    userQuest = input("Press 'p' for previous or 'n' for next ")
    if userQuest.lower() == 'p':
        pre_num = myList[myList.index(inList) - 1]
        print(pre_num)
    else:
        print('done')

【讨论】:

  • 您的代码总是打印相同的元素,因为inList 没有更新。
  • @ack 没错。我的解决方案只修复了错误,而不是逻辑。我同意你的观点,inList 应该动态更新。
【解决方案2】:
import random

myList = ['A', 'B', 'C', 'D', 'E', 'F']
inList = random.choice(myList)

# remember position of element
pos_inList = myList.index(inList)

while True:
    print(f'inList: {myList[pos_inList]}')
    userQuest = input("Press 'p' for previous or 'n' for next ")
    if 'p' in userQuest.lower():
        # decrement position
        # wrap around from 'A' to 'F' using modulo function
        pos_inList = (pos_inList - 1) % len(myList)
    else:
        print('done')
        break

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2022-01-20
    • 2011-10-29
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多