从用户输入中打印列表



自从我在Python工作以来已经有一段时间了。我有两个列表(A和B)。如果用户在" a"中类型类型,我希望输出列表a。

我似乎不记得该怎么做。

person = input('List A or B?: ')
person = str(input())
A = ["Mark","Rob","Mary"]
B = [ "Alex","Mitch","Tyler"]

for x in A:
    print x
person_dict = {
    'A': ["Mark","Rob","Mary"],
    'B': [ "Alex","Mitch","Tyler"]
}
key = raw_input("List A or B:")
print(persons_dict.get(key, None))

python 3

中的一个可能答案
def main():
    person = input('List A or B?: ')
    A = ["Mark","Rob","Mary"]
    B = [ "Alex","Mitch","Tyler"]
    myList = []
    if person == 'A':
        myList = A
    elif person == 'B':
        myList = B
    for x in myList:
        print(x)
if __name__ == "__main__":main()

我最初制作了" mylist",因此如果用户不选择其中一个选项,则不会显示任何内容。

只需确保检查响应是什么,然后设置了:

person = input("List A or B? ")
listA = ["Mark","Rob","Mary"]
listB = ["Alex","Mitch","Tyler"]
if person == "A":
    for x in listA:
        print(x)
elif person == "B":
    for x in listB:
        print(x)

注意 - 给出交互式响应时,您必须引用它。输入()解释输入,如果回复B而不是"B"

,您将获得错误

您可以这样做:

a = ["Mark","Rob","Mary"]
b = [ "Alex","Mitch","Tyler"]
person = raw_input('List A or B?: ').lower()
if person == 'a':
    print a
elif person == 'b':
    print b
else:
    print 'Try again'

有几种方法可以做到这一点,其中一些用户解释了其他用户。

我将向您展示最快(但最不安全的)方法:

# Python 3
person = input()
for x in globals()[person]:
    print(x)

示例:

>>> A = ['foo', 'bar']
>>> person = input()
A
>>> person
'A'
>>> globals()[person]
['foo', 'bar']
>>> for x in globals()[person]:
...     print(x)
foo
bar

相关内容

  • 没有找到相关文章