Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 寻找关于for循环中index()方法用法的解释_Python_For Loop - Fatal编程技术网

Python 寻找关于for循环中index()方法用法的解释

Python 寻找关于for循环中index()方法用法的解释,python,for-loop,Python,For Loop,这一行代码的这一特定部分的用途是什么: [number_sets.index(number_set)] 根据我的理解,index()是Python中的一个内置函数,它从列表开始搜索给定元素,并返回元素出现的最低索引 但是,在这种情况下,这不适用于index()的用法 # Create original list number_sets = [[2, 4, 6], [3, 6, 9], [4, 8, 12]] # Create empty list to copy into square_se

这一行代码的这一特定部分的用途是什么:

[number_sets.index(number_set)]
根据我的理解,index()是Python中的一个内置函数,它从列表开始搜索给定元素,并返回元素出现的最低索引

但是,在这种情况下,这不适用于index()的用法

# Create original list
number_sets = [[2, 4, 6], [3, 6, 9], [4, 8, 12]]

# Create empty list to copy into
square_sets = []

# Start outer for loop to iterate over inner lists
for number_set in number_sets:

    # Add a new empty list to the new list for each iteration
    square_sets.append([])
    
    # Start inner for loop to iterate over numbers and append them into the new list
    for number in number_set:
        print("The original number is %d, and the result is %d." % (number, number ** 2))
        square_sets[number_sets.index(number_set)].append(number ** 2)

print(square_sets)

索引是一种列表方法,因此语句
[number\u set.index(number\u set)]
工作原理如下:

[列表的名称。索引(元素)
,根据定义:

返回具有指定值的第一个元素的索引。

可能通过以下方式运行代码:
可以帮助您更好地理解正在发生的情况。

只是使用原始数字集列表中数字集的索引插入到方形集列表中的同一索引中。为什么您认为您的定义不适用于此示例?
[number\u set.index(number\u set)]
它在
数字集
中查找
数字集
的索引@Chris谢谢你的帮助:)我现在就知道了!@Aru谢谢你的帮助!!