Python3.6中使用元组索引列表报错,求解决方法
Hey there! Let's break down why you're hitting that error when trying to index a list with a tuple in Python 3.6, and how to fix it.
First, the core issue: regular Python lists don't support tuple-based indexing in versions 3.6 and earlier. If you tried something like my_list[(1, 2)], Python sees that tuple as a single index value—and since lists only accept integers or slices (like [:3]), it throws a TypeError: list indices must be integers or slices, not tuple.
Let's cover the two most common scenarios and their fixes:
Scenario 1: You want to get multiple elements from the list (using multiple indices in the tuple)
If your tuple contains several index values and you want to grab all those elements at once, here are two straightforward fixes:
Option 1: Use a list comprehension
Loop through the tuple's indices and collect each element individually:
my_list = ['apple', 'banana', 'cherry', 'date'] target_indices = (0, 2) selected_items = [my_list[i] for i in target_indices] # selected_items will be ['apple', 'cherry']
Option 2: Switch to a NumPy array (for vector-style indexing)
If you're used to tuple indexing from tools like NumPy, convert your list to a NumPy array first—they natively support this kind of operation:
import numpy as np my_array = np.array(['apple', 'banana', 'cherry', 'date']) target_indices = (0, 2) selected_items = my_array[target_indices] # selected_items will be array(['apple', 'cherry'], dtype='<U6')
Scenario 2: You want to index a nested list (like accessing my_list[i][j] with (i,j))
If you have a list of lists and tried using a tuple to shortcut nested indexing, you'll need to either split the tuple into separate index calls or use a helper function:
Option 1: Split the tuple into individual indices
Unpack the tuple's values to access the nested element directly:
nested_list = [['cat', 'dog'], ['bird', 'fish']] idx_tuple = (0, 1) selected_item = nested_list[idx_tuple[0]][idx_tuple[1]] # selected_item will be 'dog'
Option 2: Use a helper function for reusable nested indexing
If you need to do this often, write a small function to traverse the tuple's indices step by step:
def get_nested_element(lst, indices): current = lst for idx in indices: current = current[idx] return current nested_list = [['cat', 'dog'], ['bird', 'fish']] selected_item = get_nested_element(nested_list, (0, 1)) # selected_item will be 'dog'
If your use case is different from these two scenarios, feel free to share more details about your code—but these fixes cover the vast majority of tuple-indexing issues with lists in Python 3.6.
内容的提问来源于stack exchange,提问作者mohannad rateb

