我有以下格式的数组:
[[['roll', 'around', 'heavy', 'thing'], 'friction'],
[['chop', 'piece', 'rubber', 'stuff', 'playground'], 'source'],
[['ball', 'play', 'pet'], 'toy'],
[['used', 'exercise', 'yoga', 'pilate'], 'toy']]]
首先,我想指数第二件每一个元素,在这里,这将是friction
,source
,toy
和toy
与第一部分的二来也单独字符串,如around
或thing
。
无论我尝试什么,我都只能对整个元素编制索引,也可以[[word, word, word], word]
得到一条list indices must be integers, not tuple
错误消息。
我尝试过training_set [0]
,它给出了第一个完整的元素。training_set [0][1]
,这给了我第一个列表的第二个元素('friction'
在这里),我也可以使用来获取第一个列表的特定元素training_set [0][0][0]
。从这里开始,我陷入了困境,因为我试图获取特定子集的所有元素。
您可以使用多个链接索引,例如:
>>> your_list[0][1]
'friction'
或循环访问变量索引:
>>> for sublist in your_list:
... print(sublist[1])
friction
source
toy
toy
此外,您可以访问一个子列表的切片。例如,要从第一个子列表中获取元素2,3,4,可以使用your_list[0][0][2:5]
。
但是,如果没有显式(for
)或隐式(map
)循环,则无法同时访问来自不同子列表的元素。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句