Numpy Column Stack with Strings?

问题描述 投票:0回答:2

我正在使用numpy.column_stack并遇到问题

Input = input('Input: ')

Words = ['First','Second','Third','Fourth','Fifth','Sixth','Seventh','Eigth','Ninth']
Numbers = [0.5,1,1.25,1.5,2,3,5,10,15]
Stack = np.column_stack((Words, Numbers))

我希望实现的目标是:

输入:第二 输出:1

输入:第九 产量:15

后来我希望有一个可编辑的辅助文件来定义单词和数字列表。我不知道Column Stack是否是最好的方法,但它是我能想到的最接近的东西?

python numpy
2个回答
1
投票

根据您的编辑,您想要的是使用字典:

Words = ['First','Second','Third','Fourth','Fifth','Sixth','Seventh','Eigth','Ninth']
Numbers = [0.5,1,1.25,1.5,2,3,5,10,15]
Stack = {word:number for (word, number) in zip(Words, Numbers)}

Input = input('Input: ')
try:
    print(Stack[Input])
except KeyError:
    print('Input: {} does not exist'.format(Input))

在这个例子中,Stack被创建为使用zip的字典理解的字典。然后,您可以使用用户的Input作为字典的键。如果该键在字典中,则将打印相应的值,否则将打印一条消息,指示该键不在字典中


0
投票

您可以使用简单的列表操作将单词与数字配对:

In [283]: Numbers                                                               
Out[283]: [0.5, 1, 1.25, 1.5, 2, 3, 5, 10, 15]
In [284]: Numbers[Words.index('Fifth')]                                         
Out[284]: 2
In [285]: Numbers[Words.index('Second')]                                        
Out[285]: 1
In [286]: Numbers[Words.index('Ninth')]                                         
Out[286]: 15
© www.soinside.com 2019 - 2024. All rights reserved.