Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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 索引与在一个列表中使用另一个列表中的索引不同步_Python - Fatal编程技术网

Python 索引与在一个列表中使用另一个列表中的索引不同步

Python 索引与在一个列表中使用另一个列表中的索引不同步,python,Python,来自R,这很难理解。从列表中获取元素时,从位置0开始。 问题是,使用一个列表从另一个列表中选择项目在这里的运行速度不一样 list1 = [1,2,3,4] list2 = [1,2,3,4] for x in range(0, len(list1)): print(list1[list2[x]]) 这将导致: >> 2 >> 3 >> 4 >> IndexError: list index out of range 当我在列表1的

来自R,这很难理解。从列表中获取元素时,从位置
0
开始。 问题是,使用一个列表从另一个列表中选择项目在这里的运行速度不一样

list1 = [1,2,3,4]

list2 = [1,2,3,4]

for x in range(0, len(list1)):
    print(list1[list2[x]])
这将导致:

>> 2
>> 3
>> 4
>> IndexError: list index out of range
当我在列表1的开头添加一个额外的项目,并在列表2的末尾添加一个项目时,问题就停止了(只是因为它们不是这样同步的)

显然,我还不熟悉这种语言,使用一个列表中的值从另一个列表中选择值的正确方法是什么

这是正确的想法吗

for x in range(0, len(list1)):
    print(list1[list2[x]-1])

Python是基于0索引的
seq[0]
seq
中的第一个元素

R是基于1个索引的

所以,是的,在python中,您可以使用

list1 = [1,2,3,4]
list2 = [1,2,3,4]
for x in range(0, len(list2)):
    print(list1[list2[x]-1])
  • 范围应该上升到
    len(列表2)
    ,而不是
    len(列表1)
  • 另外,
    range(0,len(list2))
    range(len(list2))
    相同。什么时候
    range
    只传递一个参数,它被解释为
    stop
    值,默认情况下起始值为0

注意,在Python中

for x in range(...):
通常可以避免,如果可以,则更可取。相反,你可以写作

for item in list2:
    print(list1[item-1])    

item
将分配给
list2

中的每个项目。如果列表中有4个项目,则索引必须从0到3运行,因此使用值4将抛出错误。下面是一个字母示例,可能会更清楚:

list1 = [0,2,1,3]
list2 = ['a','a','d','m']

for x in list1:
    print(list2[x]),

=> a d a m

虽然无法避免丑陋的
-1
,但对于使用python的人来说,这是正常的?我们构建
list2
时首先使用的值要少一个,因此不需要减去一。它是一个自一致的系统,就像
R的
索引是自一致的。只有当从一个系统转换到另一个系统时,问题才会出现。Edsger Dijkstra已经写了。注意Python的
范围(开始,停止)
返回半开区间的值
[start,stop)
,正如Dijkstra在他的笔记中所说的那样。