Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List - Fatal编程技术网

Python 从列表的列表中拾取项目

Python 从列表的列表中拾取项目,python,list,Python,List,我有以下表格的清单: l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]] 如何将其转化为: l=[2,3,5,7,1] 我试过: l=[x[1] for x in l0] 其中: #[('x1', 3), ('x3', 7)] 编辑: 为了不丢失对元素的跟踪,还需要将输出设置为: l=[[2,3],[5,7,1]] 所以我们不用压扁 您首先必须像这样将列表展平 flat_list=[l0中的子列表中的项目对应于子

我有以下表格的清单:

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
如何将其转化为:

l=[2,3,5,7,1]
我试过:

l=[x[1] for x in l0]
其中:

#[('x1', 3), ('x3', 7)]
编辑: 为了不丢失对元素的跟踪,还需要将输出设置为:

l=[[2,3],[5,7,1]]

所以我们不用压扁

您首先必须像这样将列表展平
flat_list=[l0中的子列表中的项目对应于子列表中的项目]
然后做你的事
l=[x[1]表示平面列表中的x]

您可以在理解中添加一个额外的循环:

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]

l=[x[1] for i in l0 for x in i]
print(l)
# [2, 3, 5, 7, 1]

您可以迭代列表并将其附加到新列表中

l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]

out = []
for a in l0:
    out.append([x[0] for x in a])
print(out)

对于新问题,可以使用嵌套理解

lst0 = [[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
lst = [[t[1] for t in u] for u in lst0]
print(lst)
输出

[[2, 3], [5, 7, 1]]
我更改了列表的名称,因为
l0
l
在大多数字体中可读性不强:
l
1
太相似


另一种选择是,您可以使用
map
来实现这一点,尽管Guido不喜欢这种构造:

from operator import itemgetter

lst0 = [[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
print([list(map(itemgetter(1), u)) for u in lst0])
在Python 2中,可以省略
列表
包装器:

print [map(itemgetter(1), u) for u in lst0]

尝试使用索引,您的l0是一个列表:

(2,3,5,7,1)


变量的可怕名称可能重复
l0
谢谢,还有其他方法使其像l=[[2,3],[5,7,1]]?@最好编辑您的问题,将其作为注释是的,它会像这样[[x[1]表示子列表中的x]表示l0中的子列表]这基本上是@FHTMitchell的解决方案的非压缩版本一个简单易读的版本是的,在我打字时,他的答案没有列在这里。好的,只要列表的大小不改变就行。但是它太冗长了,而且很容易在所有这些索引中出错。是的,他必须找到一个通用公式(循环)来找到这个结果
l0=[[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]]
l=(l0[0][0][1],l0[0][1][1],l0[1][0][1],l0[1][1][1],l0[1][2][1])
print(l)