Pra*_*eek -4 python list-comprehension list python-3.x
我有一个具有特定指数的清单
list1 = [0,3,5]
Run Code Online (Sandbox Code Playgroud)
和另一个清单.
list2 = ['a','b','c','d','e','f']
Run Code Online (Sandbox Code Playgroud)
我想要一个单行代码来返回list1中提到的索引的list2项.
output = ['a','d','f']
Run Code Online (Sandbox Code Playgroud)
我知道它可能来自带有/不带lambda函数的综合for循环.
我尝试的尝试类似于下面的内容
[x for x in list2[y] if y in list1]
[m for m in list2 for f in list1]
[for x in i: list2[x]]
Run Code Online (Sandbox Code Playgroud)
这些尝试都没有给我预期的结果.
请让我知道如何实现这一目标!
只需使用list-comprehension:
[list2[i] for i in list1]
#['a', 'd', 'f']
Run Code Online (Sandbox Code Playgroud)