Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.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_Python 3.x - Fatal编程技术网

Python 获取列表列表中的上一个元素

Python 获取列表列表中的上一个元素,python,python-3.x,Python,Python 3.x,我有一个列表the_list=[[3,2,0,1,4,5],[4,2,1,3,0,5],[0,1,2,3,4,5]。如何从the_list的三个列表中随机选择的元素中打印上一个元素。如果随机选择的元素位于索引0处,则前一个元素将是列表末尾的元素。例如,如果我为列表选择rande=3,那么我将获得以下输出: 5 1 2 如何在具有最有效时间复杂性的情况下在中对此进行编码?使用list.index()方法,并利用负数从末尾索引list的事实: >>> the_list = [[3

我有一个列表
the_list=[[3,2,0,1,4,5],[4,2,1,3,0,5],[0,1,2,3,4,5]
。如何从
the_list
的三个列表中随机选择的元素中打印上一个元素。如果随机选择的元素位于索引0处,则前一个元素将是列表末尾的元素。例如,如果我为列表选择
rande=3
,那么我将获得以下输出:

5
1
2
如何在具有最有效时间复杂性的情况下在中对此进行编码?

使用
list.index()
方法,并利用负数从末尾索引
list
的事实:

>>> the_list = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5]]
>>> rande = 3
>>> for subl in the_list:
...     print(subl[subl.index(rande)-1])
...
5
1
2

最佳时间复杂度显然是
O(nm)
,其中
n
是列表的数量,
m
是列表的长度。您尝试过什么代码?如果
3
(三个)不在任何或任何人列表中会发生什么?列表中的“两个”列表
rande
元素将始终位于\u列表中的所有列表中@TigerhawkT3抱歉,这是个打字错误。
for 3

l = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5]]

>>> list(map(lambda x: x[(x.index(3) -1)],l))

[5, 1, 2]