有一些元组列表,使用列表理解可以很容易地将此列表格式化为列表列表。但是,如何使用for循环来做同样的事情?
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
[[x for x in a_tuple] for a_tuple in some_tuples]
输出将是:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我尝试使用for循环
a_tuple = []
for i in some_tuples:
for x in i:
a_tuple.append([x])
a_tuple
输出将是:
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
如何在不使用列表理解的情况下获取[[1,2,3], [4,5,6], [7,8,9]]
?
答案 0 :(得分:1)
使用list()
将元组转换为列表:
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
a_tuple = []
for i in some_tuples:
a_tuple.append(list(i))
print(a_tuple)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
答案 1 :(得分:0)
不使用列表推导的最简单方法是将内部元组映射到列表:
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
some_lists = map(list, some_tuples) # list(map(list, some_tuples)) on Python 3.x
print(some_lists) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
答案 2 :(得分:0)
你的清单理解:
print([[x for x in a_tuple] for a_tuple in some_tuples])
与:
相同final_result=[]
for a_tuple in some_tuples:
sub_result=[]
for x in a_tuple:
sub_result.append(x)
final_result.append(sub_result)
print(final_result)
输出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]