There is a list of some tuples and it would be easy to format this list to a list of lists by using a list comprehension . However, how can I do the same thing by using for loop?
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
[[x for x in a_tuple] for a_tuple in some_tuples]
The output will be:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I tried to use for loop
a_tuple = []
for i in some_tuples:
for x in i:
a_tuple.append([x])
a_tuple
The output will be:
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
How can I get [[1,2,3], [4,5,6], [7,8,9]]
without using the list comprehension ?
use list()
to convert a tuple to a 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]]
The easiest way without using list comprehension is to map your inner tuples to a list:
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]]
Your list comprehension :
print([[x for x in a_tuple] for a_tuple in some_tuples])
is same as:
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)
output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.