Python - 如何打印给定多个索引的列表的值?
Python - how to print values of a list given many indexes?
我有例如索引值:
x = [1, 4, 5, 7]
我有一个元素列表:
y = ['this','is','a','very','short','sentence','for','testing']
我想要 return 值
['is','short','sentence','testing']
当我尝试打印时说:
y[1]
它会很乐意 return ['is']
。但是,当我执行 print(y[x]))
时,它只会 return 什么都没有。我如何打印所有这些索引?奖励:然后加入他们。
这应该可以完成工作:
' '.join([y[i] for i in x])
试试这个列表组合 [y[i] for i in x]
>>> y = ['this','is','a','very','short','sentence','for','testing']
>>> x = [1, 4, 5, 7]
>>> [y[i] for i in x] # List comprehension to get strings
['is', 'short', 'sentence', 'testing']
>>> ' '.join([y[i] for i in x]) # Join on that for your bonus
'is short sentence testing'
其他方式
>>> list(map(lambda i:y[i], x) ) # Using map
['is', 'short', 'sentence', 'testing']
您将需要一个 for 循环来遍历您的索引列表,然后用索引轴化您的列表。
for i in x: #x is your list, i will take the 'value' of the numbers in your list and will be your indexed
print y[i]
> is
short
sentence
testing
如果你有numpy
包,你可以这样做
>>> import numpy as np
>>> y = np.array(['this','is','a','very','short','sentence','for','testing'])
>>> x = np.array([1,4,5,7])
>>> print y[x]
['is' 'short' 'sentence' 'testing']
我有例如索引值:
x = [1, 4, 5, 7]
我有一个元素列表:
y = ['this','is','a','very','short','sentence','for','testing']
我想要 return 值
['is','short','sentence','testing']
当我尝试打印时说:
y[1]
它会很乐意 return ['is']
。但是,当我执行 print(y[x]))
时,它只会 return 什么都没有。我如何打印所有这些索引?奖励:然后加入他们。
这应该可以完成工作:
' '.join([y[i] for i in x])
试试这个列表组合 [y[i] for i in x]
>>> y = ['this','is','a','very','short','sentence','for','testing']
>>> x = [1, 4, 5, 7]
>>> [y[i] for i in x] # List comprehension to get strings
['is', 'short', 'sentence', 'testing']
>>> ' '.join([y[i] for i in x]) # Join on that for your bonus
'is short sentence testing'
其他方式
>>> list(map(lambda i:y[i], x) ) # Using map
['is', 'short', 'sentence', 'testing']
您将需要一个 for 循环来遍历您的索引列表,然后用索引轴化您的列表。
for i in x: #x is your list, i will take the 'value' of the numbers in your list and will be your indexed
print y[i]
> is
short
sentence
testing
如果你有numpy
包,你可以这样做
>>> import numpy as np
>>> y = np.array(['this','is','a','very','short','sentence','for','testing'])
>>> x = np.array([1,4,5,7])
>>> print y[x]
['is' 'short' 'sentence' 'testing']