Reputation: 73
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?
Upvotes: 1
Views: 106
Reputation: 3543
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)
Upvotes: 0
Reputation: 1080
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)
Upvotes: 1
Reputation: 9047
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]]
Upvotes: 0