简体   繁体   中英

Python How to use for loop to fill sublists in a list

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)

Results:

[[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM