从另一个列表中的数字中查找项目在另一个列表中的位置
基于我先前的问题,我想知道是否有一种方法可以在列表中包含一个元素,然后在另一个列表中找到该位置,然后将该位置作为变量返回.例如:
Developing on my previous question I'm wondering whether there is a way to have an element in a list and find that position in another list and return what is in the position as a variable. for example:
list1 = [0,1,2,3,4]
list2 = ["0","hello","my","name","is","Daniel"]
如果用户输入数字14,则程序将以计算机将14读为1和4并在列表中找到位置的意义返回"hello Daniel".
if the user enters the number 14 the program will return "hello Daniel" in the sense that the computer reads 14 as 1 and 4 and finds the position in list as an example.
我已经厌倦了使用 [list2.index(x)for list1中的x]
,希望它可以工作,但是我一直无法更改代码,因此它确实可以工作.有没有简单的方法可以做到
I've tired using [list2.index(x) for x in list1]
hoping that it would work but I've been unable to change the code so it does work. is there a simple way to do it
您可以执行以下操作:
input_num = 123
list1 = [0, 1, 2, 3, 4] # if list1 is not dervied from input number
list2 = ["0", "hello", "my", "name", "is", "Daniel"]
print(' '.join([list2[list1.index(int(ind))] for ind in str(input_num)]))
这将导致:
hello my name
此外,我建议您查看 https://docs.python.org/2/tutorial/datastructures.html 并尝试学习.
Also, i would suggest you to look at the https://docs.python.org/2/tutorial/datastructures.html and trying things out to learn.