如何从列表中选取一个片段

2024-04-29 17:13:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,列表中的每一项都是由两个数字组成的列表:

myList = [[1,2], [4,3], [6,7]]

但是,当我尝试在索引处对列表进行切片时,我得到了一个错误。例如:

n = myList[1]

退货:

TypeError: list indices must be integers or slices, not list

那么,如何将这个列表的索引存储在一个新变量中呢?我的最终目标是能够访问主列表中每个列表中的单个值。你知道吗


Tags: orintegers列表错误not切片数字be
1条回答
网友
1楼 · 发布于 2024-04-29 17:13:06

这些工具可能会有所帮助。你知道吗

myList = [[1,2], [3,4], [5,6], [7,8], [9,0]]

# iterate through the list 
# prints the list in order 1,2,3,4,5,6,7,8,9,0
for subList in myList:
    for number in subList:
        print(number)

# index the list
myList[1] == [3,4]
myList[1][0] == 3

# slice the list
myList[1:4] == [[3,4], [5,6], [7,8]]
myList[1:]  == [[3,4], [5,6], [7,8], [9,0]]
myList[:4]  == [[1,2], [3,4], [5,6], [7,8]]

相关问题 更多 >