Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.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/16.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_List_Tuples - Fatal编程技术网

Python 如何从嵌套列表生成元组

Python 如何从嵌套列表生成元组,python,python-3.x,list,tuples,Python,Python 3.x,List,Tuples,我有一个特定的嵌套列表: paths = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't'], ['s', 'c', 'e'] 我想在每个嵌套列表中取2的元组,例如,我想作为输出: ['s', 'a'] , ['a', 'b'] ,['b', 't'] , ['s', 'c'] ,... 等等。 你知道怎么做吗?这是一个没有使用列表理解导入模块的版本: paths = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't

我有一个特定的嵌套列表:

 paths = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't'], ['s', 'c', 'e'] 
我想在每个嵌套列表中取2的元组,例如,我想作为输出:

 ['s', 'a'] , ['a', 'b'] ,['b', 't'] , ['s', 'c'] ,...
等等。
你知道怎么做吗?

这是一个没有使用列表理解导入模块的版本:

paths = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't'], ['s', 'c', 'e']]

res = [[j[i], j[i+1]] for j in paths for i in range(len(j)-1)]
print(res)
输出:

[['s', 'a'], ['a', 'b'], ['b', 't'], ['s', 'c'], ['c', 'd'], ['d', 't'], ['s', 'c'], ['c', 'e']]

一种方法是将嵌套列表理解与
zip
一起使用:

paths = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't']]

res = [[i, j] for x in paths for i, j in zip(x, x[1:])]
结果:

[['s', 'a'], ['a', 'b'], ['b', 't'], ['s', 'c'], ['c', 'd'], ['d', 't']]
输出:

[['s', 'a'], ['a', 'b'], ['b', 't'], ['s', 'c'], ['c', 'd'], ['d', 't'], ['s', 'c'], ['c', 'e']]

所需的输出与列表列表最接近。没有涉及元组。我忘了提到,在我将它们拆分为2后,我想检查每个元组是否在字典中,然后在后续任务中执行其他操作。首先看看你是否能自己做。如果你不能,那么继续搜索。如果你在几个小时后仍然被困在这里,可以作为一个单独的问题发帖。我已回滚您的更新。祝你好运
[['s', 'a'], ['a', 'b'], ['b', 't'], ['s', 'c'], ['c', 'd'], ['d', 't'], ['s', 'c'], ['c', 'e']]