简体   繁体   中英

How to convert a list comprehension to a nested loop?

I was looking through some Python code and found this line in the code:

data = [[int(x) for x in list] for list in values]  

This code basically converts strings to integers in the values of the nested list. For example:

values = [['8', '1', '1', '0', '1', '1', '0', '0'], ['9', '0', '0', '1', '0', '0', '1', '0']] 

The output becomes:

data = [[8, 1, 1, 0, 1, 1, 0, 0], [9, 0, 0, 1, 0, 0, 1, 0]]

At this moment the for loop is a nested for loop, it looks "complicated", what if I wanted to convert this into a "regular" for loops, so it becomes easier to follow but still does the same job? How would that code look like?

 data = [[int(x) for x in list] for list in values] 

this snippet is a list comprehension, to use a for loop you have to do:

data[]
for list in values:
    y = []
    for x in list:
         y.append(int(x))
    data.append(y)

Find explanation in the comments

#data = [[int(x) for x in list] for list in values]  
values = [['8', '1', '1', '0', '1', '1', '0', '0'], ['9', '0', '0', '1', '0', '0', '1', '0'], ['10', '0', '0', '1', '0', '0', '1', '0'], ['11', '0', '0', '0', '0', '0', '0', '0'], ['12', '0', '0', '0', '0', '0', '0', '0'], ['13', '0', '0', '0', '0', '0', '0', '0'], ['14', '0', '0', '0', '0', '0', '0', '0'], ['15', '0', '0', '0', '0', '0', '0', '0'], ['16', '0', '0', '0', '1', '0', '2', '3'], ['17', '1', '1', '2', '0', '1', '1', '0'], ['18', '1', '0', '0', '2', '1', '1', '2']] 

# it is similar to 
final_list = []
for list_ in values:
    # iterate over the values
    temp = []
    for c in list_:
        temp.append(int(c))
    final_list.append(temp) # be cautious you can caught with shallow copy sometime, safe side use final_list.append(temp.copy())
    
print(final_list)
[[8, 1, 1, 0, 1, 1, 0, 0], [9, 0, 0, 1, 0, 0, 1, 0], [10, 0, 0, 1, 0, 0, 1, 0], [11, 0, 0, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0, 0, 0], [13, 0, 0, 0, 0, 0, 0, 0], [14, 0, 0, 0, 0, 0, 0, 0], [15, 0, 0, 0, 0, 0, 0, 0], [16, 0, 0, 0, 1, 0, 2, 3], [17, 1, 1, 2, 0, 1, 1, 0], [18, 1, 0, 0, 2, 1, 1, 2]]

the current loop architecture will look like:

data = []
for word in values:
    nested_list = []
    for x in word:
        nested_list.append(int(x))
    data.append(nested_list)

I would suggest using list comprehension and trying to avoid naming variables with Reserved Keywords like list, if, elif

I see there're already ready answers, but tried)

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