python - Python: Initializing and filling a list of lists from another list of lists
问题描述
I have a list of lists in Python which contains a tuple For eg.
tuple_list =
[ [(a1,b1), (a2,b2).......(a99, b99)]
[(c1,d1), (c2,d2).......(c99, d99)]
.
.
.
[(y1,z1), (y2,z2).......(y99, z99)]]
I want to initialize two list of lists a_list
and b_list
In a_list
, I want it to have first index
of every tuple from tuple_list
a_list =
[ [a1, a2.......a99]
[c1, c2.......c99]
.
.
.
[y1, y2.......y99]]
and b_list
must have second index
of every tuple from tuple_list
[ [b1, b2.......b99]
[d1, d2.......d99]
.
.
.
[z1, z2.......z99]]
I tried this
a_list = [[]] * len(tuple_list )
b_list = [[]] * len(tuple_list )
for index, list in enumerate(tuple_list ):
for index2,number in enumerate(list):
a_list [index].append(number[0])
b_list [index].append(number[1])
But its giving me some different answer. How do I do it?
解决方案
您可以像这样使用列表理解来构建 a_list 和 b_list
a_list = [[t[0] for t in row] for row in tuple_list]
b_list = [[t[1] for t in row] for row in tuple_list]
推荐阅读
- arrays - 屏蔽numpy数组中的列
- java - 如何发出 if-modified-since 请求?
- hibernate - 用于排序目的的 Spring 规范左连接
- java - 字符串中的两个前字节:转换行为?
- amazon-cloudformation - 使用 CodePipeline - 将 CloudFormation 堆栈部署到另一个帐户
- python - 我们如何将 python 文件从一个目录导入到另一个目录?
- c - 使用循环在打印数组末尾打印换行符,使用 c 中的转义序列
- reactjs - React Native - 调试版本显示“欢迎使用 React Native”屏幕而不是主屏幕
- javascript - 无法从节点 api 获取响应返回到角度
- laravel - 在雄辩的条件下使用附加属性