简体   繁体   English

Python3如何从列表中检索列表

[英]Python3 How to retrieve list from a list

I want to create a user-defined input that retrieves the list within the list of stk_pairs.我想创建一个用户定义的输入来检索 stk_pairs 列表中的列表。

For example, when the input prompts the user to select which pair they want, eg 1, it means that it will retrieve the second element of the stk_pairs list;例如,当输入提示用户 select 是他们想要的对时,例如 1,则表示它将检索 stk_pairs 列表的第二个元素; in this case is [ 'C', 'D']在这种情况下是 ['C', 'D']

stk_pairs = [['A, B'],
              ['C', 'D'],
              ['E', 'F']]

print('1st pair is A and B; indicated as 0')
print('2nd pair is C and D; indicated as 1')
print('3rd pair is E and F; indicated as 2')

get_stk_pairs = input('choose which pair to compare: ')
answer = stk_pairs[get_stk_pairs]
print(answer)

However, I get this error:但是,我收到此错误:

Output Output

TypeError: string indices must be integers

Please advise!请指教!

You should make sure that the input value will be an int type to be accepted as the index of your list while by default the input is a str .您应该确保输入值是int类型,被接受为列表的索引,而默认情况下输入是str So your code should be changed to this:所以你的代码应该改成这样:

get_stk_pairs = int(input('choose which pair to compare: '))

You need to convert the user input to int (as by default it is of type str ) so that can be used as an index in retrieving the elements from the list:您需要将用户输入转换为int (默认情况下它是str类型),以便可以用作从列表中检索元素的索引:

get_stk_pairs = int(input('choose which pair to compare: '))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM