从用户输入打印列表

时间:2016-06-19 03:53:50

标签: python list user-input

自从我在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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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)

注意 - 在提供交互式响应时,您必须引用它。 input()解释输入,如果您回复B而不是"B",则会收到错误。

答案 2 :(得分:0)

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'最初为空,因此如果用户没有选择其中一个选项,它将不会显示任何内容。

答案 3 :(得分:0)

你可以这样做:

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'

答案 4 :(得分:-2)

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

我会告诉你最快(但最不安全)的方法:

# 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